C# console and windows Form development with LINQ and ADO.NET

 First install dotnet framework

install visual studio community edition



JVM(Java Virtual Machine) make java platform independent.

JVM is different for different machine.


In this blog we will learn about

  • C# console Programing and basic and advance console structure
  • Winform application basic
  • Multi Document Interface(MDI) and database operations
  • Managing database changes and CURD operations
  • User management and Login Functionality
  • Add to source control




code structure

using package_name;
using system;

namespace ProjectName
{
    class Program
    {
        static void Main(string[ ] args)
        {
            console.WrieLine("Hello world");
        }
    }
}

class name Program is actually the file name

// is used for single line comment
/*    is used for multiline comment */

Three types of control structure are supported by C#
1. Sequence
2. Decision (conditional statement)
3. Repetition

Variable are the entities in C# that store certain value and value of variable changes during program execution.

Data type in C# is like an adjective that describe variable. It tells variable what kind of data it store. 

Console.ReadLine() allow user to input and store a variable

Console.WriteLine allow us o print contents of variable/ user's input





Data types
string-words/numbers (name, license plate number) [dobble quote is used for string]
int- whole number | double/float - decimals
char - one character [Single quote is used for Char]

Declaring variable

datatype variable name
Its better to use camelCase in variable Name as it increases readability
Project Name uses PascalCase



data type and conversion


    class Program
    {
        static void Main(string[] args)
        {
            string name=string.Empty;
            int age=0;
            double salary=0.0f;
            char gender=char.MinValue;
            bool working=false;
            //prompt user for input
            Console.Write("Enter your name");
            name = Console.ReadLine();
            Console.Write("Enter your age");
            age = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter your salary");
            salary = Convert.ToDouble(Console.ReadLine());
            Console.Write("Enter your Gender (M or F");
            gender = Convert.ToChar(Console.ReadLine());
            Console.Write("Are you working (true or false): ");
            working = Convert.ToBoolean(Console.ReadLine());
            //print to screen
            Console.Write("Yourr namme is : " + name); // string concatenation
            Console.Write("Your age is {0}", age);
            Console.Write($"Your salary is: {salary}"); //string interpolation
            Console.Write("Yourr hrnfrt is : " + gender);
            Console.Write("Yourr are employee : " + working);



        }
    }

operator in c#
    class Program
    {
        static void Main(string[] args)
        {
            //basic assignment operator
            int num;
            num = 5;
            Console.WriteLine($"Assignbed value to variable: {num}");

            //arithmetic operator
            int x = 15, y = 10;
            Console.WriteLine($"Addition: {x + y}");
            Console.WriteLine($"subraction: {x - y}");
            Console.WriteLine($"multipiucation: {x * y}");
            Console.WriteLine($"Division: {x / y}");
            Console.WriteLine($"modulus: {x % y}");
            //compound assignment operators
            x += 4; //x=x+4

        }
    }


Condition Statements

types
  1. sequence
  2. Decision
  3. Selection
  4. Repetition

sequence statements basically represents the facts that program is going to execute the command in exact order that you place. i.e. line by line.
 
selection 
if statements, switch statement and ternary operators
operator used <,>,==,!= etc

 if (2 < 3)
        {
            Console.WriteLine("Yes it is");
        }
        else
        {
            Console.WriteLine("No it is not");
        }

  //switch statement

        Console.WriteLine("enter 1 or 2 or 3");
        int n;
        n = Convert.ToInt32(Console.ReadLine());
        switch (n)
        {
            case 1:
                Console.WriteLine("value is 1");
                break;
            case 2:
                Console.WriteLine("value is 2");
                break;
            case 3:
                Console.WriteLine("value is 3");
                break;

        }

     //ternary statement
        int num1=2,num2=3;
        string result;
        result =  (num1>num2)? "num1 is larger" : "num 2 is larger";
        Console.WriteLine(result);


Repetition statement
3 types of loop
for loop(Counter controlled)
  for(int i=0; i<5; i++)
        {
            Console.WriteLine(i);
        }
print from 0 to 4

while loop (Condition controlled - Pre check)
 int n=0;
        while(n < 5)
        {
            Console.WriteLine(n);
            n++;
        }

print from 0 to 4

do while loop (Condition controlled - Post check)

   int n = 0;
        do
        {
            Console.WriteLine("this block will execuet without checking condition");

        }
        while (n < 5);
        {
            Console.WriteLine(n);
            n++;
        }

foreach - honorable mention
Foreach(var item in collection(list) )
{

}




Method and return types

Prototype - Defines the function (type, name and parameters)

Definition - Has the code. It contains the code block

Function Call - Makes the function

DRY - Don't Repeat Yourself

YAGNI - You Aren't Going To Need It






Void is commonly used return types that means it does not return any thing.
before function name there will be data type and that data type will tell you what type of data the function is returning.

Void functions - completes a task and moves along

void PrintName()
{
    Console.WriteLine("Jidesh Baidya")
}

void Addition(int n1,int n2)
{
    Console.WrteLine($" The Sum of {n1} and {n2} is {n1+n2}"
}

int LargestNumber(int n1,n2,n3)
{
int largest=n1;
if(n1<n2)
{
largest=n2
}
if(largest<n3)
{
largest=n3
}

Value Returning function - completes a task, returns a result

PrintName();
Addition(1,2)

int result=LargestNumber(3,4,5)
Console.WrieLine($"The largest number is: {result}");

String Manipulation function

string firstName="Jidesh"
string lastName="Baidya"
DateTime date = DateTime.Now;

//print to screen
Console.WriteLine(firstName);
Console.WriteLine("String will be printed");
Console.WriteLine($"my full name is {firstname} {lastname}");
Console.WriteLine($"my full name is {0} {1}", firstname,lastname);

// string length

int length = firstname.Length;
Console.WriteLine($"Your name is {length} letters long");

// Replace string parts


string newName= firstName.Replace('t','k');

//Append to other string variable

string fullName= string1 + " " + string 2

//split string
string[] splitName = fullName.Split('v;);

for(int i =0; i<length;i++)
{
console.WriteLine(splitName[i});
}


//compare strings

string nullstring=null;
string emptyStrnig="";
string whitespaceString= " ";


if(string.IsNullOrEmpty(nullString))
{
 Console.WriteLine("String is null");
}

if(firstName == LastName)
{
 Console.WriteLine("Names are equal");
}

if(firstName != LastName)
{
 Console.WriteLine("Names are not equal");
}


int comparisionResult = string.Comare(firsName, lastName);
if(comparisionResult = 0)
{
 Console.WriteLine("Names are equal");

}
else
{
 Console.WriteLine("Names are not equal");

}


//convert to string

string convertedString = string.Empty

int number =1235433234;

convertedString=number.ToString();
convertedString= 123213532154.ToString();



Date time manipulation Function

//Empty datetime

DateTime date = new DateTime()

/create a datetime from date and time


DateTime dateOfBirth = new DateTime(1996,05,25);
ConsoleWriteLine("my dob is " + dateOfBirth);
ConsoleWriteLine("my dob is date " + dateOfBirth.Date);

ConsoleWriteLine("Day of week: {0} " ,dateOfBirth.DayOfWeek);
ConsoleWriteLine("Day of Year: {0} " ,dateOfBirth.DayOfYear);
ConsoleWriteLine("Time of Day: {0} " ,dateOfBirth.TimeOfDay);;
Console.WriteLine('Tick: {0}",dateOfBirth.Ticks);
Console.WriteLine("Kind: {0}", dateOfBirth.Kind);






// create datetime from current time stamp
DateTime now = DateTime.Now;
Console..WriteLine("The time now is :"+now);



//create a DateTime from a string
DateTime datefromString = DateTime.Parse("1/31/2021",cultureInfo.InvarantCulture);


Console.WriteLine("he date time froom string is :"+ datefromString);


//Add Additional Time
now.AddHours(1);
Console.WrieLine("One hour from now is :" now.AddHour(1));


//Datetime tricks

Console.WriteLine("Time as a numeral:; " + now.Ticks);




//Date only

DateOnly dateOnlyOfBirth = DateOnly.FromDateTime(dateOfBirth);



//time only

TimeOnly timeOnly = TimeOnly.FromDateTime(now);



Exception Handling

used to handle error

try - try a block attemps an operation
catch - catch any fatal error or exception
finally - whether the try or the catch was sucessful, do this
throw - end the program execution with the error



Console.WriteLine("Enter 1st no");
int num1= Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter 2st no");
int num1= Convert.ToInt32(Console.ReadLine());

int quotient= num/num2;
Console.WriteLine("Result is: " + quotient.ToString());

try
{
 int quotient=num1/num2;
Console.WriteLine("Result is: " + quotient.ToString());
}
catch (DivideByZeroException ex)
{
    Console.WrieLine($"Illegal Operation: {ex.Message}");
}
catch (Exception ex)
{
 throw ex;
}
finally 
{
Console.WriteLine("This is the finally block");
}



Arrays

collection of values




//Declare Fixed size Array

int[] grades = new int[5];
 // 5 space addresses - 0,1,2,3,4
if  n is the size of array the array has address between 0 to n-1



// Add values to Fixed size Array
grade[0]=32
grade[1]=43
grade[2]=32
grade[3]=53
grade[4]=67

grade[5] ==> this will be indexoutofrange exception as array is of size 5 i.e from 0 to 4


we can also initialize as follow

int[] grades = new int[] {32,43,32,53,67 };




//other way to initialize array dynamically

for (int i = 0;i<grades.Length;i++)
{

Console.WrteLin("Enter Grade: ");
grades[i]=Convert.ToInt32(Console.ReadLine());

}

Console.WriteLine("The grade you have entered are");
for( int i = 0; i< grades.Length; i++)
{
Console.WriteLine(grades[i]);
}

// Print values in fixed size Array

// Declare Variable sized Array


string[] studentNames= new string[] {"std1","std2","std3"};


// Add values to variable sized Array


// Print values in variable sized array


List
dynamic collection type

continuous homogeneous collection of data 


List<string> names= new List<string>();


//add valeus to list

names[0] = "Jidesh"
names.Add("sabin");

string anem = string.Empty;
Console.WriteLine("Enter Names:");
while (name != "-1")  //while (name.Equals("-1")==false)while (!name.Equals("-1")==false)
{
Console.Write("Enter Name: ");
name=onsole.ReadLine();
names.Add(name);

if(string.IsNullOrEmpty(name) && !name.Equals("-1"))
{

    names.Add(name);
    Console.Write($"{name} was inserted sucessfully");


}

}

//print value in the list



Console.WriteLine("Printing name via for loop");
for (int i=0;i<=name.Count;i++)
{

Console.WriteLine(names[i]);

}




Consoel.Writeline("Pringting name via for each loop");

foreach( string item in names)
{

Console.WriteLine(item);

}


//remove

names.Remove("sabin");



Object Oriented Programming


OOP allows us to create us our own data type i.e. with the help of class


// premitive datatype
such data types are data type that we have used when we started it off
eg int, string, char, bool

these datatype doesnot provide everything we want


class is like blueprint of an object
object is manifestation of class



// Single responsibility Principle


namespace is actually name of the folder




//defining class

internal class Person
{

// propeties when publc
public int Id { get; set; }
public string FirstName {get; set;}
public string LastName { get; set;}
public int Age { get; set; }

// Field when private
private double _salary {get; set;}

public void setSalary(double salary) 
{
_salary= salary;
}

public double getSalary() 
{
return _salary;

public string getFullNamme()
{
 return $"{FirstName} {LastName}";
}
public string getFullName(string middleName)
{
 return $"{FirstName} {middleName} {LastName}";
}
}



Person person = new();
Person person1 = new Person();
Person person2= new Person();
Person person3= new Person();





its easy to differentiate method with property
method will have cube where as property will be screw driver in visual studio intelligence 

Console.WriteLine("Enter first Name");
person.FirstName = Console.ReadLine();

Console.WriteLine("Enter Last Name");
person.LastName = Console.ReadLine();


Console.WriteLine("Enter age");
person.age = Convert.ToInt32(Console.ReadLine()) ;


int salary = Convert.ToInt32(Console.ReadLine());


person.setSalary(salary);

Console.WrteLine("First name is : " + person.FirstName);
Console.WriteLine("Last Name is : " + person.LastName);
Console.WriteLine("Age is: " + person.Age);
Console.WriteLine("Salary is: " + person.getSalary());


Encapsulation

method overloading can be very important when you want to give your users option to carry out the same kind of operation or different options with the same method



string middleName = String.Empty;
Console.WriteLine("Enter middle name");
middleName= Console.ReadLine();

if (string.IsNullOREmpty(middleName))
{
Console.WriteLine("Full Name is :" + person.getFullName());
}
else
{
Console.WriteLine("Full Name is :" + person.getFullName(middleName));
}


Static Class
Static class is one that cannot be instantiated 

Console is example of static class
we don' have to instantiate it



internal static class DateUtil
{
 public static int YearOfBirth(int age)
{
    return DateTime.Now.Year - age;
}
public static int YearIfBirth(DateTme dateOfBirth)
{
if(dateOfBirth ==null)
    return 0;
rerun dateOfBirth.Year;
}
public static int Age(DateTime dateOfBirth)
{
if(dateOfBirth == null)
    return 0;
return DateTime.Now.Year - dateOfBirth.Year
}
}


Console.WriteLine("Age is: " + person.Age);
Console.WriteLine("Year of birth is: "+DateUtil.yearOfBirth(person.Age));



Inheritance

getting the property  of some other class is inheritance


abstract class Shape
{
public double height{get;set;}

public double length {get; set; }

public double getArea()
{
}

}

class Cube : Shape, IShape
{
public double Width {get; set;}


public double getArea()
{
return Length*Length;
}

}


Class Triangle :Shape
{
 public doouble Hypotenese {get; set;}


public double getArea()
{
reurn .5*Length*Height;
}

}

Class Rectangle: Shape, IShape

{
public double Width { get; set; }

public double getArea()
{
return Length*Width;
}

}

Interface is lighter weight class meaning it can define properties, methods
..... rather it can declare them but doesn't define them

interface IShape
{
 double getArea();
}


Cube cube = new Cube();
var triangle = new Triangle();
var cube = new Cube();
var rectangle = new Rectangle();


Console.WrieLiine("Enter length:");
int length = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Width: ");
int width = Convert.ToInt32(Console.ReadLine());


Console.WriteLine("Ener Height: ");
int height = Convert.ToInt32(Console.ReadLine());

cube.Length= length
Cube.Width = width
cube.Height = height

triangle.Length = length
triangle.Height = height

rectangle.Length= length
rectangle.Width = width;


Console.WriteLine("Cube Areais: " + cube.getArea());
Console.WriteLine("Cube Volume is: "+ cube.getVolume()):


Console.WriteLine("Triangle Area is: "+ triangle.GetArea());

Console.WriteLine("Rectangle Area is: " + rectangle.GetArea());


Constructor is function which is used to initialize 

type ctor and tab to generate constructor automatically

constroctor are public and they have same name as the class
they may or may not have parameters


Winform application on visual studio 2022

Fist go to control panel ==> program and features 

choose visual studio 2022

right and click on change

put check mark in winform application

and lunch visual studio





Comments