Class is one of the important components in object-oriented programming (OOP). It has its own specific objects and properties. We can consider an object as an instance of a class. In this article, we will understand in detail, the C# and its features.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Is a Class in C# ?

We can consider class as a pattern of a particular object. In a real-life scenario. Each object has its own shape, color, and functionalities. For example, the luxury car Audi, has its own many features, like color, interior, exterior, shape, and speed. If a particular organization manufactures the car, it should consider its own specifications as an object of the car type as luxury. So, each car of the brands, Lamborghini, BMW, Mercedez is a class and every individual actual car is an object of the luxury car class.

Example:

class AutoCar

    {

        private string color;

        public AutoCar(string color)

        {

            this.color = color;

        }

        public string Feature()

        {

            return "This car is " + Color;

        }

        public string Color

        {

            get { return color; }

            set { color = value; }

        }

    }

C# Access Modifiers

Access modifiers provide certain types of accessibility levels of a member of the type of a class within the scope of accessibility. For example, we have a public class access modifier that is accessible to everyone without any constraints. On the other side, we use an internal class that can be accessed within the code assembly.

Definitions of Access Modifiers:

  • Public: This is the standard access modifier, and members of the class can be accessed from any other defined code in the same assembly. a public class we can access it externally without any restrictions.
  • Private: Using a private access modifier, code can be accessed within the same class definition with the restriction. We can consider it as the default access modifier.
  • Protected: With this modifier, its types and modifiers can be accessed using the code in the same class and also within its derived class.
  • Internal: With this modifier type, members can be accessed with each code in the same assembly without any other assembly.
  • Protected internal: Access is limited to the current assembly and types derived from its associated class. In the defined project, all its derived class members can access its variables.
  • Private protected: Access is restricted to its associated class or types derived from the associated class inside the current assembly.

Become a Certified UI UX Expert in Just 5 Months!

With The Best-in-class UI UX ProgramExplore Program
Become a Certified UI UX Expert in Just 5 Months!

Types of Access Modifiers

Public Modifier

Here we define the public keyword to access its modifier for certain types and members. Public access is the common allowed access level i.e it’s accessible to everywhere without any restriction. 

Example:

In the below example num is direct access.

    class Program  

    {  

        class AccessModifier 

        {  

            public int num;  

        }  

        static void Main(string[] args)  

        {  

            AccessModifier ob = new AccessModifier();  

            //Direct access to public members  

            ob.num = 100;  

            Console.WriteLine("Number of one value in main {0}", ob.num);  

            Console.ReadLine();  

        }  

    }  

Private Modifier

Private access is the restricted permitted access level.

We can access private members within the body level of the class; we cannot access it by the object and derived class.

Example:

Here we can see num is not accessible outside the class.

   class Program  

    {  

        class AccessModifier  

        {  

            public int num;  

            int num1;  

        }  

        static void Main(string[] args)  

        {  

            AccessModifier ob = new AccessModifier ();  

            //Direct access to public members  

            ob.num = 200;  

            //Access to private member is not permitted  

            ob.num1 = 40;  

            Console.WriteLine("Number one value in main {0}", ob.num1);  

            Console.ReadLine();  

        }  

    }  

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Protected Modifier

We can access a protected member modifier only within the class of its object declaration, and from its derived class which is declared by its member.

The protected access modifier is accessible using inheritance within and outside the package. We can use a protected access modifier to the data member, constructor, and method.

Below is the code example of a scenario where if we try to access a protected member in static main, it is not available.

Example: 

class Program  

    {  

        class BaseClass 

        {  

            protected int num;  

        }  

        class DerivedClass : BaseClass  

        {  

            public int num;  

            static void Main(string[] args)  

            {  

                Base ob = new Base();  

                Derived dv = new Derived();  

                dv.num = 20;  

                // Access to protected member as it is inherited by the derived class  

                dv.num1 = 90;  

                Console.WriteLine("Number2 value {0}", dv.num1);  

                Console.WriteLine("Number1 value which is protected {0}", dv.num);  

                Console.ReadLine();  

            }  

        }  

    } 

Internal Modifier

  • We can use internal as a keyword to access its types and members. 
  • We can define a class as internal or we can use its member as internal. 
  • These internal members are only accessible inside its files and the same assembly (.dll).
  • This modifier is restricted only to its defined class inside your current project assembly (dll).
  • If we use it with the public, it can be accessible with its objects of the class and its associated derived classes.
  • If we use it with the internal then we cannot access its object and its derived classes.

Protected Internal Modifier

  • In c#, the protected internal modifier is applied to define that access is restricted to the current assembly or types determined from the containing class. The type or member can be accessed from any code in the corresponding assembly or any determined class in another assembly.
  • In different concepts, a protected internal member can be accessed from any class in the same assembly with its derived classes. 
  • It defines certain types of combinations of protected and internal.

C# Field

  • In the C# programming language, we define the field as a variable of a certain type which we can declare within a class.
  • Fields are also the members of their associated types.
  • In a class, we have an instance and a static field. We can define the field for a declaration of the variable which has its own private and protected accessibility.
  • We can use it as a field that defines the generic block of declaration in the code.
  • A field is a variable of each type that is held directly in a class or struct. A class has instance fields, static fields.

Example 1:

This AutoCar class has three class members: two fields and one method.

class AutoCar 

{

  // Class members

  string color = "blue";        // field

  int maxSpeed = 200;          // field

  public void fullThrottleSpeed()   // method

  {

    Console.WriteLine("The blue car can go fast as much it can");

  }

}

Example 2:

  class AutoCar 

  {

    string color = "blue";

    int maxSpeed = 200;

    static void Main(string[] args)

    {

      AutoCar Obj = new AutoCar();

      Console.WriteLine(Obj .color);

      Console.WriteLine(Obj .maxSpeed);

    }

  }ll

}

Output 

Class_in_C_Sharp_1

C# Constructor

  • A constructor is a specific method that is utilized to initialize objects. 
  • The benefit of a constructor is that we can call it when a certain object of a class is declared. 
  • We can use it to define the primary values for fields.
  • A constructor in C# is a feature of a class.  
  • We define it as a method within the class when we create an object in the class.
  • We initialize the code in the constructor() with the same name as the main class.
  • A class can hold its various overloaded constructors.

Example:

class AutoCar

  {

    public string model;  // Define a field

    // Define a class constructor for the AutoCar class

    public AutoCar()

    {

      model = "Audi"; // Define the initial value for model

    }

    static void Main(string[] args)

    {

      AutoCar Mercedes = new AutoCar();  // Define an object of the AutoCar Class (this will call as the constructor)

      Console.WriteLine(Mercedes.model);  // Print the value of model

    }

  }

Output

Class_in_C_Sharp_2.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

C# Method

  • We define a method as a function in the c# programming, which can be declared with the parentheses ().
  • C# presents amazing predefined methods: 

For example Main(), using which we can build our custom methods to accomplish certain actions.

Example:

class Test

{

  static void Method() 

  {

    // code to be executed

  }

}

The below code example is the perfect scenario to call a method using the C# function

class Test

  {

    static void Method()

    {

      Console.WriteLine("Hello I am executed!");

    }

    static void Main(string[] args)

    {

      Method();

    }

  }

Output

Class_in_C_Sharp_3

C# Property

  • In C# programming, property plays an important role to set and define each data field and value.
  • We can define the get and set the property using Get accessor we can apply to return a property value and Set accessor is utilized to define a value. In c#, these properties can be classified as read-write, read-only, or write-only.
  • To implement this, we need to define the fields and their variables with the “Private” modifier.
  • Define the public get and set the methods with its properties for access and modify the value of a private field.
  • A property is like a mix of a variable and a method, and it enables two pair methods: get and set method:

Example:

Program1 to define the properties 

class PersonCls

  {

    private string name;  // field

    public string Name    // property

    {

      get { return name; }

      set { name = value; }

    }  

  }

Program2 to call the person function which has defined the “Name”

class Test

  {

    static void Main(string[] args)

    {

      PersonCls Obj = new PersonCls();

      Obj.Name = "Testname";

      Console.WriteLine(Obj.Name);

    }

  }

Output

Class_in_C_Sharp_4

Auto-Implemented Property

  • In C#, advance version 3.0 defines the concept of auto-implemented properties, Auto-implemented properties allow developers to quickly define a property of a particular class without declaring to define the code to Get and Set the property.
  • It executes code in compact and understandable ways.
  • Auto-implemented properties allow you to immediately define a property of a class without defining and writing the get and set the property in a class.

Example:

class AutoImp

{

    public List<int> SampleList { get; set; }

    public Foo()

    {

        SampleList  = new List<int>();

    }

}

Namespace in C#

  • In C# programming, namespaces are applied to reasonably manage classes, interfaces, etc. 
  • The namespaces in C# can be defined in many ways indicating that individual namespaces can include different namespaces further. 
  • The .NET framework already comprises a number of official namespaces. Example: System, System.Net, System.IO, System.text, System.xml, and so on.
  • In enhancement to these namespaces, the user can determine their individual custom namespaces.
  • We can declare a namespace with the keyword “Namespace” as a user-defined name.
  • Namespaces are used to build the classes. It serves to control the range of methods and classes in advance level of programming projects.

Example:

namespace <yournamespace_name>

{

// Define Classes.

}

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

We hope this article helped you understand classes in C#. In this article, we discussed the concept of code structure of different types of defining the class with the access modifiers which will be helpful to professional developers from Java and .net backgrounds, application architectures, and other learners looking for information on JavaScript events.

If you are looking to upgrade your skill set, you can sign up on our SkillUp platform, a Simplilearn initiative that offers numerous free online courses to help with the basics of multiple programming languages, including JavaScript. You can also opt for our Full-Stack Web Development Certification Course in which you'll learn modern coding techniques with bootcamp-level intensity and gain all you need to be a full-stack technologist.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449