Class, Object, Constructor in C#

Class:

Object: Instance of a Class.

Naming Conventions in C#

In C# we use 2 types of Naming Conventions.

  1. Pascal Case : First letter of every world should be upper case.
  2. camel Case : Only First letter of first word is lower case and after that first letter of every word is upper case. Camel case is used in naming of parameters in methods.

Class Members

1. Instance : Accessible from Object

var obj = new Student();
obj.ShowResult();

2. Static : Accessible from Class

Console.WriteLine();

Constructors in C#

    • Constructor is not having any return type, not even void.
    • Every class is having default constructor which compiler automatically creates. This default constructor is called when we create instance of any class. This constructor is used to initialize the class members with its default values according to the data types of members.
    • If we create some new user defined constructors except default constructor of any class then compiler will not create default constructor. In this case, User has to declare default constructor too.
    • You can pass control from one constructor to another constructor using “this” keyword. This is called constructor chaining.
  public class Student
    {
        public string name;
        public int rollNumber;

        public Student() { }
        public Student(int r) : this("", r) { }
        public Student(string n) : this(n, 0) { }
        public Student(string n, int r)
        {
            name = n;
            rollNumber = r;
        }
        public void PrintRollNumber()
        {
            Console.WriteLine("Roll number:" + rollNumber);
        }

        static void Main(string[] args)
        {
            var student = new Student(100);

            student.PrintRollNumber();
        }
    }

 

Written by 

Leave a Reply

Your email address will not be published. Required fields are marked *