• Home
  • Class and Objects

Class and Objects

Agenda

C# Class and Objects

C# Class and Objects – Sample Code

Syntax to declare a class:

       class <class_name> {

field;


method;


}


//Defining a Student class.


Public class Student{


//defining fields


Public int rollno= 1;


Public string name = “Rahul";


//defining methods


public void schoolName()


{


Console.WriteLine("State Government School");


}


}


static void Main(){


Student student1=new Student(); //creating an object of Student


//Printing values of the object in Console


Console.WriteLine(student1.rollno); //accessing member through reference variable


Console.WriteLine(student1.name);


}

public class Student
{
//define fields
public int rollno;
public string name;
public int age;
//Define Method
public void schoolName()
{
Console.WriteLine("Kendriya Vidyala");

}
}
class Program
{
int i = 25;
public void add(int a, int b)
{
Console.WriteLine(a + b);
}
public int multiply(int x, int y)
{
int result = x* y;
return result;
}


static void Main()
{
Student s1 = new Student();
s1.rollno= 1;
s1.name = "Rahul";
s1.age = 10;
Console.WriteLine(s1.rollno); //print default values of data types
Console.WriteLine(s1.name);
Console.WriteLine(s1.age);
s1.schoolName();

Student s2 = new Student();
s2.rollno = 2;
s2.age = 11;
s2.name = "Rajesh";
Console.WriteLine(s2.rollno);
Console.WriteLine(s2.name);
Console.WriteLine(s2.age);
s2.schoolName();

Student s3 = new Student();
s3.rollno = 3;
s3.name = "Vinay";
s3.age = 9;
Console.WriteLine(s3.rollno);
Console.WriteLine(s3.name);
Console.WriteLine(s3.age);
s3.schoolName();

Program obj = new Program();
Console.WriteLine(obj.i);
obj.add(10 ,20);
Console.WriteLine(obj.multiply(15, 10));


Console.ReadKey();
}
}