Classes and Structs

We can use classes and structs to build new types.

Classes and structs are a data structure that encapsulates a set of data and behaviors.

The data and behaviors are the members of the class or struct.

A class or struct type is like a blueprint.

After class or struct type declaration we can create instances or objects at run time.

Suppose we create a class called Person and variable p is Person type, the p is said to be an object or instance of Person.

We can define multiple instances of the same Person type, for example, p1, p2, p3.

p1, p2, p3 can have different values in its properties and fields.

A class is a reference type, which means p1 hold only a reference to the Person object.

A struct is a value type.

In the following example, Rectangle is defined with two members. An instance (object) of Rectangle is created in the Main method, and the object's methods and properties are accessed by using dot notation.


        // Class definition.
        public class Rectangle
        {
            public int Width;
            public int Height;
        }
        
        public class MainClass{
           public static void Main(){
              Rectangle r = new Rectangle();
              
              r.Width = 5;
           }
        
        }

Encapsulation

All methods, fields, constants, properties, and events must be declared within a type.

These are called the members of the class or struct.

In C#, there are no global variables or methods.

The program's entry point, the Main method, must be declared within a class or struct.

The following list includes all the various kinds of members that may be declared in a class or struct.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.