C# Class

C# Code Snippets Class
Share:

About

In this code snippet, we’ll take a look at classes in C#.

A class is like a blueprint to make an instance of an object. Inside a class, you can define class members like methodsproperties, etc. Depending on the access modifier(public, private, …) set for each member we can control to who that specific member will be accessible. 

Once you create a class you must create an instance of it to make an object. Only after creating an instance of a class can you access its members. Except if you mark a class member as static then you will be able to use it without creating an instance of its class.

Let’s look at the code example below to see how to make a class.

Code:

using System;

namespace @class
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating an instance of MyClass.
            MyClass MC = new MyClass();

            //Calling the MyMethod() method from the object of MyClass.
            MC.MyMethod();

            //Assigining values to our properties.
            MC.MyProperty = 10;
            MC.MySecondProperty = 15;

            //Getting the values from our properties.
            Console.WriteLine(MC.MyProperty);
            Console.WriteLine(MC.MySecondProperty);

            Console.ReadLine();
        }
    }

    class MyClass
    {
        //Visual studio shortcut for implementing a property:
        //1. write: prop
        //or write: propfull     
        //2. pres TAB twice

        //Short way of implementing a property.
        public int MyProperty { get; set; }

        //Long way of implementing a property.
        //You can for example add some code for validation.
        //This way you can ensure that a value fits in a certain range of values before assigning it. 
        private int myVar;

        public int MySecondProperty
        {
            get { return myVar; }
            set
            {
                if (value > 0)
                {
                    myVar = value;
                }
            }
        }

        public void MyMethod()
        {
            Console.WriteLine("Hi.");
        } 
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger