variables:
int s; //delclaring s
s = 5; // initializing s with value 5
Compile time Initialization:-
using System;
class demo
{
int d;
static void Main()
{
int T =54;
Console.WriteLine("The value of T is: " + T );
demo dem = new demo();
Console.WriteLine("The value of d is: " + dem.d);
}
}
Run time Initialization:-
using System;
class flight
{
int = 54;
static void Main()
{
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The value of num is:" + num);
}
}
Lambda Expressions:-
using System;
using System.Collections.Generic;
using System.Linq;
class bike
{
public string Name{get; set;}
public int price {get; set;}
class mygoodtimestarts
{
static void Main()
{
List<bike> bikes = new List<bike>()
{
new bike{Name = "haiyabusa" , price = 1554555},
new bike{Name = "R15" , price = 255556},
new bike{Name = "Glamour" , price = 78556}
};
var names = bikes.Select(x => x.Name)
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine();
}
}
}
Using Lambda Expressions with Anonymous Type:-
using System;
using System.Collections.Generic;
using System.Linq;
class car
{
public string Name{get; set;}
public int price {get; set;}
}
class demo
{
static void Main()
{
List<car> cars = new List<car>()
{
new car{Name = "jaguar" , price = 735455},
new car{Name = "BMW" , price = 923544},
new car{Name = "Ranze Rover" , price = 1224455}
};
var mycars = cars.Select(x => new{price = x.price , lastletter = x.Name[0]});
foreach(var item in mycars)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
Delegates:
a. Singlecast Delegate:-
using System;
namespace mylearning
{
class program
{
public delegate void delmethod();
public class Mygoodtimestarts
{
public static void Display()
{
Console.WriteLine("How are you!");
}
public static void show()
{
Console.WriteLine("Who are you!");
}
public void print()
{
Console.WriteLine("Where are you!");
}
}
static void Main(string[] args)
{
delmethod del1 = Mygoodtimestarts.show;
delmethod del2 = new delmethod(Mygoodtimestarts.Display);
Mygoodtimestarts obj = new Mygoodtimestarts();
delmethod del3 = obj.print;
del1();
del2();
del3();
Console.WriteLine();
}
}
}
b. Multicast Delegate:-*/
using System;
namespace MyLearning
{
class MYPROGRAM
{
public delegate void delmethod(int x , int y);
public class Mygoodtimestarts
{
public void plus_method1(int x , int y)
{
Console.WriteLine("You are in plus_method1 Zone");
Console.WriteLine(x+y);
}
public void subtstract_method2(int x, int y)
{
Console.WriteLine("You are in subtstract_method2 Zone");
Console.WriteLine(x-y);
}
static void Main(string[] args)
{
Mygoodtimestarts obj = new Mygoodtimestarts();
delmethod del1 = new delmethod(obj.plus_method1);
del1 += new delmethod(obj.subtstract_method2);
del1(84 , 54);
Console.WriteLine();
del1 -= new delmethod(obj.plus_method1);
del1(55 , -21);
Console.ReadLine();
}
}
}
}
/* Databinding in Gridview:-
using System;
using System.Data;
using System.Data.SqlClient;
using Systsem.Configuration;
public partial class_Default:System.Web.UI.Page;
{
protected void Page_Load(object sender EventArgs e)
{
if(!IsPostBack)
{
ShowData();
}
}
string cs = Configuration.ConnectionStrings["DBCS"].ConnectionString;
protected void ShowData()
{
DataTable dt = new DataTable();
SqlConnection Con = new SqlConnection(cs);
SqlAdapter adapter = new SqlAdapter("select * from customer" , Con);
Con.Open();
adapter.Fill(dt);
Con.Close();
if(dt.Rows.Count > 0 )
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Partial class:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Partial.classes
{
public Partial class ourclass
{
public int Add(int x, int y)
{
return(x+y);
}
}
public Partial class ourclass
{
public int Sub(int x, int y)
{
return(x-y);
}
}
public class testclass
{
public void test()
{
ourclass ourcls = new ourclass();
ourcls.Add(45 , 24);
ourcls.Sub(35 , 11);
}
}
}
Constructors:
1.Default Constructor:-
using System;
namespace NewConstructor
{
public class Employee
{
public string NameOfEmloyee;
public string AddressOfEmployee;
public Employee()
{
NameOfEmloyee = "Charan Kumar";
AddressOfEmployee = "Ongole";
}
}
class program
{
static void Main()
{
Employee emp = new Employee();
Console.WriteLine("Employee name is :"+emp.NameOfEmloyee);
Console.WriteLine("Employee Address is :"+emp.AddressOfEmployee);
Console.ReadLine();
}
}
}
2.Parameterized Constructor:-
using System;
namespace NewConstructor
{
public class Employee
{
public string Employeename;
public string EmployeeAddress;
public Employee(string name , string address)
{
Employeename = " Chiranjeevi";
EmployeeAddress = " Hyderabad";
}
}
class program
{
static void Main()
{
Employee emp1 = new Employee("Chiranjeevi" , "Hyderabad");
Console.WriteLine("Name of Employee :"+ emp1.Employeename);
Console.WriteLine("Address of Employee :"+ emp1.EmployeeAddress);
Console.ReadLine();
}
}
}
3.Static Constructor:-
using System;
namespace NewConstructor
{
public class Employee
{
public static readonly long Baseline;
public string EmployeeName;
public string EmployeeAddress;
//static Constructor
static Employee()
{
Baseline = DateTime.Now.Ticks;
Console.WriteLine("static Constructor is executes first.");
}
//Default Constructor
public Employee()
{
EmployeeName = "Durga";
EmployeeAddress = "Bheemavaram";
Console.WriteLine("executes after static Constructor.");
}
class program
{
static void Main(string[] args)
{
Employee emp2 = new Employee();
Console.WriteLine("Name of Employee:"+ emp2.EmployeeName);
Console.WriteLine("Address of Employee:"+ emp2.EmployeeAddress);
Console.ReadLine();
}
}
}
}
4.private Constructor:-
using System;
namespace NewConstructor
{
public class Employee
{
private Employee()
{}
public static int CurrentEmployee;
public static int IncreamentEmployee()
{
return ++CurrentEmployee;
}
}
class program
{
static void Main(string[] args)
{
Employee.CurrentEmployee = 150;
Console.WriteLine("Current Employee is:"+ Employee.CurrentEmployee);
Console.WriteLine("Increament Employee is:"+ Employee.IncreamentEmployee());
Console.ReadLine();
}
}
}
Method OverLoading and Overriding:
i.OverLoading:-
using System;
namespace mycsharp
{
class MYPROGRAM
{
public int Add(int num1 , int num2)
{
return(num1+num2);
}
public int Add(int num1, int num2,int num3)
{
return(num1+num2+num3);
}
public float Add(float num1,float num2)
{
return(num1+num2);
}
public string Add(string value1, string value2)
{
return(value1 + " " + value2);
}
static void Main()
{
MYPROGRAM objprgm = new MYPROGRAM();
Console.WriteLine("Add with two int parameters:"+ objprgm.Add(7,8));
Console.WriteLine("Add with three int parameters:"+ objprgm.Add(5,8,3));
Console.WriteLine("Add with two float parameters:"+ objprgm.Add(3,9));
Console.WriteLine("Add with two string parameters:"+ objprgm.Add("Iam" , " chiru"));
Console.ReadLine();
}
}
}
ii.Overriding:-
using System;
namespace DemoCsharp
{
class BaseClass
{
public virtual int Add(int num1, int num2)
{
return (num1 + num2);
}
}
class ChildClass: BaseClass
{
public override int Add(int num1, int num2)
{
if (num1 <= 0 || num2 <= 0)
{
Console.WriteLine("Values could not be less than zero or equals to zero");
Console.WriteLine("Enter First value : ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter First value : ");
num2 = Convert.ToInt32(Console.ReadLine());
}
return (num1 + num2);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass baseClassObj;
baseClassObj = new BaseClass();
Console.WriteLine("Base class method Add :" + baseClassObj.Add(-3, 8));
baseClassObj = new ChildClass();
Console.WriteLine("Child class method Add :" + baseClassObj.Add(-2, 2));
Console.ReadLine();
}
}
}
Collections:
a.Non-Generics:
1.ArrayList:-
using System.Collectins;
protected void Button1_click(object sender EventArgs e)
{
ArreyList al = new ArreyList();
string name = "chiru keerthi";
int x = 10;
DateTime d = DateTime.Parse("05-aug-1997");
al.Add(name);
al.Add(x);
al.Add(d);
foreach(object o in al)
{
Response.Write(o);
Response.Write("<br>");
}
}
2.HashTable:-
using System.Collections;
protected void Button2_click(object sender EventArgs e)
{
HashTable hstbl = new HashTable();
hstbl.Add("ora" , "oracle");
hstbl.Add("vb" , "vb.net");
hstbl.Add("asp" , "asp.net");
hstbl.Add("cs" , "c#.net");
foreach(Dictionaryentry d in hstbl)
{
Response.Write(d.key +""+ d.values);
Response.Write("<br>");
}
}
3.SortedList:-
using System;
protcted void Button3_click(object sender EventArgs e)
{
SortedList sl = new SortedList();
sl.Add("ora" , "oracle");
sl.Add("vb" , "vb.net");
sl.Add("cs" , "c#.net");
sl.Add("asp" , "asp.net");
foreach(Dictionaryentry d in sl)
{
Response.Write(d.keys + "" + d.value);
Response.Write("<br>")
}
}
4.stack:-
using System;
protected void Button4_click(object sender EventArgs)
{
stack stk = new stack();
stk.Push("cs.net");
stk.Push("vb.net");
stk.Push("asp.net");
stk.Push("sqlserver");
foreach(object o in stk)
{
Response.Write(o + "<br>");
}
}
5.Queue:-
using System;
protected void Button5_click(object sender EventArgs)
{
Queue q = new Queue();
q.Enqueue("cs.net");
q.Enqueue("vb.net");
q.Enqueue("asp.net");
q.Enqueue("sqlserver");
foreach(object o in q)
{
Response.Write(o + "<br>");
}
}
b.Generic Collections:
1.List:-
using System.Collections.Generic;
static void Button1_click(object sender EventArgs)
{
List<int> lst = new List<int>();
lst.Add(100);
lst.Add(200);
lst.Add(300);
lst.Add(400);
foreach(int i in lst)
{
Response.Write(i + "<br>");
}
}
2.Dictionary:
using System.Collections.Generic;
protected void Button1_Click(object sender, EventArgs e)
{
Dictionary<int, string> dct = new Dictionary<int, string>();
dct.Add(1, "cs.net");
dct.Add(2, "vb.net");
dct.Add(3, "vb.net");
dct.Add(4, "vb.net");
foreach (KeyValuePair<int, string> kvp in dct)
{
Response.Write(kvp.Key + " " + kvp.Value);
Response.Write("<br>");
}
}
3.SortedList:-
using System.Collections.Generic;
protected void Button3_click(object sender EventArgs e)
{
SortedList<string , string> sl = new SortedList<string , string>();
sl.Add("ora" , "oracle");
sl.Add("vb" , "vb.net");
sl.Add("cs" , "cs.net");
sl.Add("asp" , "asp.net");
foreach(KeyValuePair<string,string> kvp in sl)
{
Response.Write(kvp.Key + " " +kvp.value);
Response.Write("<br>");
}
}
4.Stack:-
using System.Collections.Generic;
protected void Button4_click(object sender EventArgs e)
{
stack<string> stk = new stack<string>();
stk.Push("cs.net");
stk.Push("vb.net");
stk.Push("asp.net");
stk.Push("sqlserver");
foreach(string s in stk)
{
Response.Write(s + "<br>");
}
}
5.Queue:-
using System.Collections.Generic;
protected void Button5_click(object sender EventArgs e)
{
Queue<string> q = new Queue<string>();
q.Enqueue("cs.net");
q.Enqueue("vb.net");
q.Enqueue("asp.net");
q.Enqueue("sqlserver");
foreach(string s in q)
{
Response.Write(s + "<br>");
}
}
AccessModifiers:
1.Public Modifier:-
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();
//Direct access to public members
ob1.num1 = 100;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
2.Private Modifier:-
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
int num2;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();
//Direct access to public members
ob1.num1 = 100;
//Access to private member is not permitted
ob1.num2 = 20;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
Inheritance:
a.Single Inheritance:-
public class AccountCreditInfo //Base Class
{
public string Credit()
{
return "Balance is Credited";
}
}
public class AccountDebitInfo:AccountCreditInfo //Derived Class
{
public string Debit()
{
Credit();
return "Balance is Debited";
}
}
b.Hierarchical Inheritance:-
public class A //Base class
{
public string msg()
{
return "This is A class Method";
}
}
public class B:A
{
public string info()
{
msg();
return "This is B class Method";
}
public class C:A
{
public string getinfo()
{
msg();
return "This is B class Method";
}
}
}
c.MultiLevel Inheritance:-
public class person
{
public string persondet()
{
return "This is the persondet class";
}
}
public class Bird:pesron
{
public string Birddet()
{
persondet();
return "This is the Birddet class";
}
}
public class Animal:Bird
{
public string Animaldet()
{
persondet();
Birddet();
return "This is the Animal class";
}
}
d.Multiple Inheritance using interface:-
public interface IA //interface1
{
string setImgs(string a);
}
public interface IB //interface2
{
int getAmount(int Amt);
}
public class Icar:IA , IB //implementation
{
public int getAmount(int amt)
{
return 100;
}
public string setImgs(string a)
{
return "This is a car";
}
}
Boxing & UnBoxing:
Boxing:-
using System;
class mycollege
{
static void Main(string[] args)
{
int Number = 2024;
object obj = Number;
Number = 212;
System.Console.WriteLine("value-type value of number is :{0}" , Number);
System.Console.WriteLine("object-type value of number is :{0}" , obj);
}
}
UnBoxing:-
using System;
class myschool
{
static void Main()
{
int number = 245;
object obj = number;
int i = (int)obj;
System.Console.WriteLine("value-type value of number is :{0}" , number);
System.Console.WriteLine("object-type value of number is :{0}" , obj);
}
}
switch statement:-
using System;
class jaguar
{
static void Main()
{
int age = 18;
switch(age)
{
case 1:
Console.WriteLine("case 1 is not eligible");
break;
case 5:
Console.WriteLine("case 5 is not eligible");
break;
case 7:
Console.WriteLine("case 7 is not eligible ");
break;
case 18:
Console.WriteLine("case 18 is eligible");
break;
default:
Console.WriteLine("no matches found");
break;
}
}
}
Loops:-
a.Whileloop:-
using System;
class mybuilt
{
static void Main()
{
int num = 25;
while(num <= 30)
{
Console.WriteLine("my world!");
num++ ;
}
}
}
b.do while:-
using System;
class mucourage
{
static void Main()
{
int r = 24;
do
{
Console.WriteLine("My Basics!");
r++;
}
while(r<30);
}
}
c.forloop:-
using System;
class myhotel
{
static void Main()
{
//int h = 54;
for(int h=54 ; h<=58 ; h++)
{
Console.WriteLine("Good Basics!");
// h++;
}
}
}
d.Nested Loops:-
using System;
class nestedloop
{
static void Main()
{
for(int s=10 ; s<=15 ; s++)
{
for(int h=7 ; h>4 ; h--)
{
Console.WriteLine("My good time started!");
}
}
}
}
e.break statement;-
using System;
class mytrainingstarted
{
static void Main()
{
for(int a=11 ; a<16 ; a++)
{
if(a==13)
break;
Console.WriteLine("All is Well!");
}
}
}
f.continue statement:-
using System;
class vehicle
{
static void Main()
{
for(int w=8 ; w>=4 ; w--)
{
if(w==6)
continue;
Console.WriteLine("Everything is fine!");
}
}
}
Control statements:
a. if:-
using System;
class demo
{
static void Main()
{
string name = "chiru";
if(name=="karan")
{
Console.WriteLine("it is matched!");
}
}
}
b. if-else:-
using System;
class demo
{
static void Main()
{
string car = "Ranze Rover";
if(car=="BMW")
{
Console.WriteLine("it's my car");
}
else
{
Console.WriteLine("It's not a my car!");
}
}
}
c. else if:-
using System;
class business
{
static void Main(string[] args)
{
string name = "subbu";
if(name == "shekar")
{
Console.WriteLine("It's not my name!");
}
else if(name == "hari")
{
Console.WriteLine("it's not your name");
}
else if(name == "subbu")
{
Console.WriteLine("Yeah! This is my Name!");
}
else
{
Console.WriteLine("None of the above!");
}
}
}
d.nested if:-
using System;
class myclass
{
static void Main()
{
int num = 256;
if(num == 256)
{
//nested if statement
// will only be executed if statement
//Above statement is true
if(num > 250)
{
Console.WriteLine("It is successful!");
}
else
Console.WriteLine("It is not successful!");
}
}
}
e.Switch case statement:-
using System;
class mycollege
{
static void Main()
{
string day = "Thursday";
switch(day)
{
case "sunday":
Console.WriteLine("It is sunday!");
break;
case "monday":
Console.WriteLine("It is monday!");
break;
case "saturday":
Console.WriteLine("Its a saturday!");
break;
case "Thursday":
Console.WriteLine("Yeah! Today is Thursday.");
break;
default:
Console.WriteLine("None of the above!");
break;
}
}
}
f. nested switch case:-
using System;
class cammando
{
static void Main()
{
int num = 455;
switch(num)
{
case 455:
Console.WriteLine("Today is good Day!");
switch(num-1)
{
case 454:
Console.WriteLine("Take care of health!");
switch(num-2)
{
case 453:
Console.WriteLine("Take care of your family too!");
break;
}
break;
}
break;
case 400:
Console.WriteLine("Take care of your carrier!");
break;
default:
Console.WriteLine("Take care!");
break;
}
}
}
Another Example:
if-else statement:-
using System;
class General
{
static void Main()
{
string topic;
string Category;
topic = "Encapsulation";
if((String.Compare(topic , "Constants")==0)||
(String.Compare(topic , "Inheritance")==0)||
(String.Compare(topic , "abstract class")==0))
{
Category= "My Class";
}
else if((String.Compare(topic , "TypeCasting")==0)||
(String.Compare(topic , "Generics")==0)||
(String.Compare(topic , "Variables")==0))
{
Category = "Advantages";
}
else if((String.Compare(topic , "Encapsulation")==0)||
(String.Compare(topic , "Collections")==0)||
(String.Compare(topic , "Delegates")==0))
{
Category = "OOPS Concept.";
}
else
{
Category = "My Component";
}
System.Console.WriteLine("Category is " + Category);
}
}
Using switch statement instead of if-else statement:-
using System;
class cricket
{
static void Main()
{
string topic;
string Category;
topic = "Abstraction";
switch(topic)
{
case "Variables":
case "Constants":
case "Delegates":
Category = "operators";
break;
case "Generics":
case "Polymorphism":
case "Triggers":
Category = "Comments";
break;
case "Lambda Expressions":
case "ArrayList":
case "Abstraction":
Category = "OOPS Concept!";
break;
default:
Category = "My Component";
break;
}
System.Console.WriteLine("Category is " + Category);
}
}
Identifiers:-It may be a class,method and Variables
using System;
class mycomponent
{
static void Main()
{
int a=22;
int b=25;
int c=a+b;
Console.WriteLine("The sum of two numbers is:{0}",c);
}
}
Initializing an Object:-
using System;
public class mylappy
{
string lappyname;
string lappyversion;
int lappyprice;
string lappycolor;
public mylappy(string lappyname , string lappyversion , int lappyprice , string lappycolor)
{
this.lappyname = lappyname;
this.lappyversion = lappyversion;
this.lappyprice = lappyprice;
this.lappycolor = lappycolor;
}
public string Getlappyname()
{
return lappyname;
}
public string Getlappyversion()
{
return lappyversion;
}
public int Getlappyprice()
{
return lappyprice;
}
public string Getlappycolor()
{
return lappycolor;
}
public string ToString()
{
return("Hi dude! my lappy name is " + this.Getlappyname() + "\nMy lappy version,price and color are:" + this.Getlappyversion() +"," + this.Getlappyprice() + "," + this.Getlappycolor());
}
public static void Main()
{
mylappy laptop = new mylappy("hp laptop" , " Ryzon-i3" , 43000 , " white");
Console.WriteLine(laptop.ToString());
}
}
patterns:-
1. using System;
class pattern
{
static void Main()
{
int Rows = 6;
for(int i = 1 ; i <= 6 ; i++)
{
for(int j = 1 ; j <= i ; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
2.using System;
class Program
{
static void Main()
{
int rows = 5; // You can change this value to adjust the number of rows
for (int i = 1; i <= rows; i++)
{
// Print spaces for alignment
for (int s = 1; s <= rows-i; s++)
{
Console.Write(" ");
}
// Print the repeating digit for the current row
for (int j = 1; j <= i; j++)
{
Console.Write(i);
}
Console.WriteLine(); // Move to the next line after each row
}
}
}
3. using System;
class Program
{
static void Main()
{
int rows = 5; // You can change this value to adjust the number of rows
for (int i = 1; i <= rows; i++)
{
// Print the numbers for the current row
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine(); // Move to the next line after each row
}
}
}*/
Write, Run & Share C# code online using OneCompiler's C# online compiler for free. It's one of the robust, feature-rich online compilers for C# language, running on the latest version 8.0. Getting started with the OneCompiler's C# compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C# and start coding.
OneCompiler's C# online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
string name;
name = Console.ReadLine();
Console.WriteLine("Hello {0} ", name);
}
}
}
C# is a general purpose object-oriented programming language by Microsoft. Though initially it was developed as part of .net but later it was approved by ECMA and ISO standards.
You can use C# to create variety of applications, like web, windows, mobile, console applications and much more using Visual studio.
| Data Type | Description | Range | size |
|---|---|---|---|
| int | To store integers | -2,147,483,648 to 2,147,483,647 | 4 bytes |
| double | to store large floating point numbers with decimals | can store 15 decimal digits | 8 bytes |
| float | to store floating point numbers with decimals | can store upto 7 decimal digits | 4 bytes |
| char | to store single characters | - | 2 bytes |
| string | to stores text | - | 2 bytes per character |
| bool | to stores either true or false | - | 1 bit |
datatype variable-name = value;
When ever you want to perform a set of operations based on a condition or set of few conditions IF-ELSE is used.
if(conditional-expression) {
// code
}
else {
// code
}
You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.
Switch is an alternative to If-Else-If ladder.
switch(conditional-expression) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
// code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement) {
// code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1.
data-type[] array-name;
Method is a set of statements which gets executed only when they are called. Call the method name in the main function to execute the method.
static void method-name()
{
// code to be executed
}