+92 332 4229 857 99ProjectIdeas@Gmail.com

A Complete Class Example (C#.net)



A Complete Class Example:
The following code shows you a complete class example... declaring variables, setter and getters, constructors and methods related to class.
Declaring class objects in Main(). accessing private members of class. etc etc...


Code

public class MyClass
{
       private string name;

To generate getter/setter select the "name" field and right click on it and go to Rafactor and choose Encapsulate Field, it will automatically generate the get/set. see below

       // Getter/Setter of “name” field
       public string Name
       {
           get { return name; }
           set { name = value; }
       }

       private int age;

       // Getter/Setter of “age” field
       public int Age
       {
           get { return age; }
           set { age = value; }
       }

       // Constructor with zero arguments
       public MyClass()
       {
           this.name = string.Empty;
           this.age = 0;
       }

       // Parameterized Constructor
       public MyClass(string n, int a)
       {
           this.name = n;
           this.age = a;
       }

       public void displayFields()
       {
           Console.Write("Name is : " + this.name + "\n" + "Age is : " + this.age);
       }
}

public static void Main(String[] args)
{

   // Way First To Declare Object 
    
    MyClass obj = new MyClass();
    obj.displayFields();

   // Way Second To Declare Object 

    new MyClass("abdullah", 4).displayField();
  
    MyClass obj3 = new MyClass();
    obj3.Name = "osama";
    obj3.Age = 21;
    obj3.displayFields();

    MyClass obj4 = new MyClass("saad", 21);
    obj4.displayFields();
}
  

 

0 comments: