Labels

slider

Recent

Navigation

C# Classes and Objects with examples

Learn about C# classes and objects with examples

C# Classes and Objects with examples

Among all types of Object-oriented programming languages, C# is the best recommended improved OOPS language for a complete enhanced Programming career. C# language endows with complete support for object-oriented programming which includes EPI (encapsulation, polymorphism, and inheritance).

C# Classes and Objects with examples

Encapsulation

Encapsulation refers to a group of relevant properties, methods, and other programming members that are considered as a single unit or object. By using Encapsulation, we can use a unit of the object for various programming purposes.

Polymorphism

Polymorphism is meant for having multiple classes that can be incorporated interchangeably, even though every class applies similar properties or methods in diversified approaches. Throughout Polymorphism method, you don’t have to use different properties or methods for different classes.

Inheritance

Inheritance explains the capability to make new classes according to an existing class and hence, creating multiple classes is easier through inheritance method.

Classes and objects

The terms class and object are used to describe the specific type of objects, and the occurrence of classes, respectively. So, we call the task of creating an object as instantiation. Throughout the blueprint analogy, a class is considered as a blueprint, and an object is a creation made from the class blueprint. Hope, now you must have clarified the relationship between class and blueprint.
For defining a class you need to use: ‘class SampleClass { }’

Structures

When you don't desire any assistance for the polymorphism or inheritance, C# provides useful types called structures.
For defining a structure, we use code: 

struct TCStruct 
{
}

Class members

Each class can have different class members with appropriate properties to explain the class data, appropriate methods to explain the class behavior, and appropriate events that allow communication between various classes and objects.
Fields and Properties
Fields and properties stand for information that an object possesses truly. Fields are similar to variables as they can be read or set straightly, subject to appropriate access modifiers.
For defining a field that is accessible from within any instances of the class, we use code

public class TCClass 
{
string TCField;
}
The properties of a class contain ‘get and set’ accessors to put more control on setting or returning of values. In C# you will be able to create a private field to store the property value or use auto-applied properties that create this field robotically and provide the basic logic for the property process.
For defining an auto-applied property, we use code

class TCClass
{
public int TCProperty { get; set; }
}
If you want to execute some added operations for reading and writing of the value of the property, first define a field to store the value of the property and give the basic logic to store and retrieve the same as follows:

class TCClass
{
    private int _sample;
    public int Sample
    {
        // Return the property value stored from a field.
        get => _sample;
        // Store the property value in the field.
        set =>  _sample = value;
    }
}
Most of the properties possess some methods to set and get the value of property value. On the other hand, you can set read-only or write-only properties to control them from being updated or view. In C#, you can also skip the get or set procedure of property. Nevertheless, the properties that are auto-implemented cannot be write-only and the auto-implemented properties that are Read-only can be set in builders of the carrying class.

Defining Method of class

A method can be simply explained as an action that an object can truly perform.
Following are the codes for defining a class method:

class TCClass
{
    public int TCMethod(string tcParam)
    {
        // Insert code here
    }
}
There are a number of applications, or overrides in a class for the same method that varies in the number of parameters or parameter types.
To override a method

public int TCMethod(string tcParam) { }
public int TCMethod(int tcParam) { }
In most cases, you declare a method within a class definition. However, C# also supports extension methods that allow you to add methods to an existing class outside the actual definition of the class.

Constructors

Constructors are the methods of a class that are performed automatically when a given type of object is created. Generally, the constructors declare the data members of a new object, and a constructor can run only for one time when a class is created. In addition, the constructor code often runs before the other code in a class. On the other hand, you can make multiple constructors override in the same process as for any other procedure.
Following are the codes for defining a class constructor:

public class TCClass
{
    public TCClass()
    {
        // Add code here
    }
}

Finalizers

A finalizer is often used to destruct class instances and clean up the unmanaged sources. Especially in .NET, the garbage collector functions as a finalizer which automatically handles the provision and discharge of memory for the controlled objects in your C# application.

Events

Events help a class or object to inform other classes or objects when an interesting event happens. The class that raises the event is known as the publisher and the classes that receive the event are subscribers. Overall, the event is dependent upon the Publishers and subscribers.
The event keyword is used to declare an event in a class and call upon the event delegate to create an event.
Now, use the += operator to subscribe to an event and use the -= operator, to unsubscribe from an event.

Nested classes

When a class is defined within another class is known as a nested class and the nested class is declared as private. Find following codes:

class Container
{
    class Nested
    {
        // Add code here.
    }
}
In order to create a the nested class instance, you need to use the container class name, dot(.), and the name of the nested class. See the codes:

Container.Nested nestedInstance = new Container.Nested()

Access modifiers and access levels

All classes and members of the class can state their level of access to other classes throughout the access modifiers in C#.

C# Access Modifier and Definition

  • Public Member - It can be accessed by any code within the same assembly or other assembly with reference.
  • Private Member - It can only be accessed directly by code only in the same class.
  • Protected Member - This member can only be used by code in a derived class, or same class.
  • Internal Member - The internal member can be used by any code only in the same assembly.
  • Protected Internal Member - The protected member can be used by any code written in the same assembly, or by the derived class from another assembly.
  • Private Protected Member - This member can be used by the same class code or by a derived class from the base class assembly.

Instantiating classes

First, create an instance of the class to create an object, and then you can give values to the properties of instance and fields and call on class methods.
Find following codes:

TCClass tcObject = new TCClass();
// Set a property value.
tcObject.tcProperty = "TC String";
// Call a method.
tcObject.TCMethod();
To set property value at the time of the class instantiation method, use object initializers:

// Set a property value.
var tcObject = new TCClass
{
    FirstProperty = "A",
    SecondProperty = "B"
};

Static Classes and Members

A static class member is a property, method, or field that is shared by all class instances. In C#, the static classes contain only static members and hence cannot have an instance. Static members are also unable to access non-static fields, properties, or methods. But, for accessing the static member, use the class name without creating an object of the same class:
Following are the codes for defining a static member:

static class TCClass
{
    public static string TCString = "TC String";
}
//Accessing the static member
Console.WriteLine(TCClass.TCString);

Anonymous types

Anonymous types help you to create objects exclusive of writing the definition of a class for the type of data. Ultimately, the compiler creates a class for you as an option. This anonymous class has no proper usable name and carries the properties you mention in defining the object.

Following are the codes for the creation of an anonymous type instance:


// tcObject is an instance of a simple anonymous type.
var tcObject = new
{
    FirstProperty = "A",
    SecondProperty = "B"
};
Hope the above session must help you out understand the class and objects along with file, properties, and events when you work on an interface. You can easily pass the .Net interviews in C# language with the help of the above codes.
Share

Anjan kant

Outstanding journey in Microsoft Technologies (ASP.Net, C#, SQL Programming, WPF, Silverlight, WCF etc.), client side technologies AngularJS, KnockoutJS, Javascript, Ajax Calls, Json and Hybrid apps etc. I love to devote free time in writing, blogging, social networking and adventurous life

Post A Comment:

0 comments: