What are Properties in C-sharp and how to use them?

In this article I will explain the property in C# along with practical demonstration which will help you to understand it in a simple way.

Difference between Property and Methods

Property

  1. Property is implicitly called using calling convention

  2. Property works on compile and runtime.

Method

  1. Method is explicitly called

  2. Methods works on runtime.

Practical: Showing how to use property


using
System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Properties_Csharp

{

class Program

{

public class PropertyClass

{

string name;

int age;

static string co_name;

static int rollno;

// Static Property

public static string _co_name

{

get

{

return co_name;

}

set

{

co_name = value;

}

}

public static int Rollno

{

set

{

rollno = value;

}

get

{

return rollno;

}

}

public string p_name

{

get

{

return name;

}

set

{

name = value;

}

}

public int p_age

{

get

{

return age;

}

set

{

age = value;

}

}

}

static void Main(string[] args)

{

PropertyClass ob1 = new PropertyClass();

PropertyClass.Rollno = 90;

Console.WriteLine(PropertyClass.Rollno);

PropertyClass._co_name = "George";

string compnay = PropertyClass._co_name;

Console.WriteLine(PropertyClass._co_name);

ob1.p_age = 23;

ob1.p_name = "Peter";

Console.WriteLine(ob1.p_age);

Console.WriteLine(ob1.p_name);

Console.ReadLine();

}

}

}


I would be glad to share my knowledge and waiting for your feedback to increase my knowledgebase.