Properties in C# | The complete Tutorial
Properties in C Tutorial ACTE

Properties in C# | The complete Tutorial

Last updated on 01st Feb 2022, Blog, Tutorials

About author

Karan Baski (C# .Net Developer )

Karan Baski is a C# .NET developer expert and subject specialist who has experience with Git, WPF,VB,.NET Framework,.NET Core, SVN,HTTP,.NET technology stack, WPF, C#, SQL Server, Web API, and ASP.NET. His articles help the learners get insights into the domain.

(5.0) | 19624 Ratings 1843
    • Introduction to C# Properties
    • Accessors
    • Unique Properties
    • Use of C# Properties
    • C# Properties Example
    • Illustration of C# Properties
    • Programmed Properties (Short Hand)
    • Exemplification
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction to C# Properties :-

    • Properties are named individuals from classes, constructions, and connection points. Part factors or strategies in a class or constructions are called Fields.
    • Properties are an expansion of fields and are gotten to utilizing a similar sentence structure.They use accessors through which the upsides of the private fields can be perused, composed or controlled.
    • Properties don’t name the capacity areas. All things being equal, they have accessors that perused, compose, or process their qualities.
    •  C# Properties
      C# Properties
    • For instance, let us have a class named Student, with private fields for age, name, and code. We can’t straightforwardly get to these fields from outside the class scope, yet we can have properties for getting to these private fields.

      Accessors :-

      The accessor of a property contains the executable explanations that aides in getting (perusing or registering) or setting (composing) the property. The accessor revelations can contain a get accessor, a set accessor, or both. For instance −


        // Announce a Code property of type string:

        public string Code {

        get {

        bring code back;

        }

        set {

        code = esteem;

        }

        }


        // Announce a Name property of type string:

        public string Name {

        get {

        bring name back;

        }

        set {

        name = esteem;

        }

        }


        // Pronounce an Age property of type int:

        public int Age {

        get {

        bring age back;

        }

        set {

        age = esteem;

        }

        }


      Model :

      The accompanying model exhibits utilization of properties −


        utilizing System;

        namespace tutorialspoint {

        class Student {

        private string code = “N.A”;

        private string name = “not known”;

        private int age = 0;


        // Proclaim a Code property of type string:

        public string Code {

        get {

        bring code back;

        }

        set {

        code = esteem;

        }

        }


        // Pronounce a Name property of type string:

        public string Name {

        get {

        bring name back;

        }

        set {

        name = esteem;

        }

        }


        // Pronounce an Age property of type int:

        public int Age {

        get {

        bring age back;

        }

        set {

        age = esteem;

        }

        }

        public abrogate string ToString() {

        return “Code = ” + Code +”, Name = ” + Name + “, Age = ” + Age;

        }

        }


        class ExampleDemo {

        public static void Main() {

        // Make another Student object:

        Understudy s = new Student();

        // Setting code, name and the age of the understudy

        s.Code = “001”;

        s.Name = “Zara”;

        s.Age = 9;

        Console.WriteLine(“Student Info: {0}”, s);

        //allow us to build age

        s.Age += 1;

        Console.WriteLine(“Student Info: {0}”, s);

        Console.ReadKey();

        }

        }

        }


      Whenever the above code is arranged and executed, it delivers the accompanying outcome −

      Understudy Info: Code = 001, Name = Zara, Age = 9

      Understudy Info: Code = 001, Name = Zara, Age = 10


      Unique Properties :-

      A theoretical class might have a theoretical property, which ought to be executed in the determined class. The accompanying system represents this −


        utilizing System;

        namespace tutorialspoint {

        public theoretical class Person {

        public theoretical string Name {

        get;

        set;

        }

        public unique int Age {

        get;

        set;

        }

        }

        class Student : Person {

        private string code = “N.A”;

        private string name = “N.A”;

        private int age = 0;


        // Pronounce a Code property of type string:

        public string Code {

        get {

        bring code back;

        }

        set {

        code = esteem;

        }

        }


        // Proclaim a Name property of type string:

        public abrogate string Name {

        get {

        bring name back;

        }

        set {

        name = esteem;

        }

        }


        // Pronounce an Age property of type int:

        public supersede int Age {

        get {

        bring age back;

        }

        set {

        age = esteem;

        }

        }

        public abrogate string ToString() {

        return “Code = ” + Code +”, Name = ” + Name + “, Age = ” + Age;

        }

        }


        class ExampleDemo {

        public static void Main() {

        // Make another Student object:

        Understudy s = new Student();

        // Setting code, name and the age of the understudy

        s.Code = “001”;

        s.Name = “Zara”;

        s.Age = 9;

        Console.WriteLine(“Student Info:- {0}”, s);

        //allow us to expand age

        s.Age += 1;

        Console.WriteLine(“Student Info:- {0}”, s);

        Console.ReadKey();

        }

        }

        }


      At the point when the above code is ordered and executed, it creates the accompanying outcome −

      Understudy Info: Code = 001, Name = Zara, Age = 9

      Understudy Info: Code = 001, Name = Zara, Age = 10

      C# Properites doesn’t have capacity area. C# Properites are expansion of fields and gotten to like fields.

      The Properties have accessors that are utilized to set, get or process their qualities.


    Course Curriculum

    Learn C# Certification Training Course to Build Your Skills

    Weekday / Weekend BatchesSee Batch Details

      Use of C# Properties :-

    • C# Properties can be perused just or compose as it were.
    • We can have rationale while setting esteems in the C# Properties.
    • We make fields of the class private, so that fields can’t be gotten to from outside the class straightforwardly. Presently we are compelled to involve C# properties for setting or getting values.

      C# Properties Example :-

      1.< using System;

      2.< public class Employee

      3.< {

      4.< private string name;

      5. {}

      6. public string Name

      7. {

      8. Get

      9. {

      10. bring name back;

      11. }

      12. Set

      13. {

      14. name = esteem;

      15. }

      16. }

      17.}

      18. class TestEmployee{

      19. public static void Main(string[] args)

      20. {

      21. Employee e1 = new Employee();

      22. e1.Name = “Sonoo Jaiswal”;

      23.< Console.WriteLine("Employee Name: " + e1.Name);

      24.< }

      25. }

      26. }

      Yield:

      Worker Name: Sonoo Jaiswal


      C# Properties Example 2: having rationale while setting esteem

    • using System;
    • public class Employee
    • {
    • private string name;
    • {}
    • public string Name
    • {
    • Get
    • {
    • bring name back;
    • }
    • Set
    • {
    • name = value+” JavaTpoint”;
    • }
    • }
    • }
    • }
    • class TestEmployee{
    • public static void Main(string[] args)
    • {
    • Employee e1 = new Employee();
    • e1.Name = “Sonoo”;
    • Console.WriteLine(“Employee Name: ” + e1.Name);
    • }
    • }

      Yield:

      Worker Name: Sonoo JavaTpoint


    Course Curriculum

    Get JOB Oriented C# Training for Beginners By MNC Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

      C# Properties Example 3: read-just property :

      1. using System;

      2. public class Employee

      3. {

      4. private static int counter;

      5. }

      6. public Employee()

      7. {

      8. Counter++;

      9. }

      10. public static int Counter

      11. {

      12. Get

      13. {

      14. bring counter back;

      15. }

      16. }

      17. }

      18. class TestEmployee{

      19. public static void Main(string[] args)

      20. {

      21. Employee e1 = new Employee();

      22. Employee e2 = new Employee();

      23. Employee e3 = new Employee();

      24. //e1.Counter = 10;//Compile Time Error: Can’t set worth

      25. }

      26. Console.WriteLine(“No. of Employees: ” + Employee.Counter);

      27. }

      28. }

      Yield:

      No. of Employees: 3


      Properties are exceptional kinds of strategies that give an adaptable system to classes for uncovering private fields. Consequently these are called accessors.

      There are two kinds of accessors under properties. These are:

      • The get property accessors.
      • The set property accessors.

      Illustration of C# Properties :-

        using System;

        public class BoardMembers

        {

        private string mname, val = “Karlos ray”;

        public string memberName

        {

        get

        {

        return mname;

        }

        set

        {

        mname = val;

        }

        }

        }

        class TestBoardmem {

        public static void Main(string[] args)

        {

        BoardMembers b1 = new BoardMembers();

        b1.memberName = ” Karlos Ray “;

        Console.WriteLine(” Board member name is: ” + b1.memberName);

        }

        }


      Various Characteristics and Situations to Get and Set Accessors:

      • Peruse and Write Properties: If your C# property holds both the get and the set strategies.
      • Peruse Only Properties: If your C# property holds just, get the technique characterized in it.
      • Compose Only Properties: If your C# property holds just a set technique characterized in it.
      • Auto-Implemented Properties: If there is no extra rationale related with your C# accessors, then, at that point, auto-executed property gets carried out.

      Properties and Encapsulation :-

      Before we begin to clarify properties, you ought to have a fundamental comprehension of “Embodiment”. The significance of Encapsulation, is to ensure that “delicate” information is stowed away from clients. To accomplish this, you should:

      • pronounce fields/factors as private
      • give public get and set strategies, through properties, to access and refresh the worth of a private field Properties.

      Model :

        class Person

        {

        private string name;//field

        public string Name//property

        {

        get { return name; }//get technique

        set { name = esteem; }//set technique

        }

        }


      Model clarified :-

    • The Name property is related with the name field. It is a decent practice to involve a similar name for both the property and the private field, however with a capitalized first letter.
    • The get strategy returns the worth of the variable name.
    • The set technique appoints a worth to the name variable. The worth watchword addresses the worth we allot to the property.
    • On the off chance that you don’t completely get it, investigate the model underneath.
    • Presently we can utilize the Name property to access and refresh the private field of the Person class:

    Model :

        class Person

        {

        private string name;//field

        public string Name//property

        {

        get { return name; }

        set { name = esteem; }

        }

        }

        class Program

        {

        static void Main(string[] args)

        {

        Individual myObj = new Person();

        myObj.Name = “Liam”;

        Console.WriteLine(myObj.Name);

        }

        }

        The result will be:

        Liam


      Programmed Properties (Short Hand) :-

      C# likewise gives a method for utilizing short-hand/programmed properties, where you don’t need to characterize the field for the property, and you just need to compose get; and set; inside the property.

      The accompanying model will deliver a similar outcome as the model above. The main contrast is that there is less code:


      Model :

        Utilizing programmed properties:

        class Person

        {

        public string Name//property

        { get; set; }

        }

        class Program

        {

        static void Main(string[] args)

        {

        Individual myObj = new Person();

        myObj.Name = “Liam”;

        Console.WriteLine(myObj.Name);

        }

        }

        The result will be:

        Liam


      Exemplification :-

    • Better control of class individuals (lessen the chance of yourself (or others) to wreck the code)
    • Fields can be made perused provided that (you just utilize the get strategy), or compose provided that (you just utilize the set technique)
    • Adaptable: the developer can transform one piece of the code without influencing different parts
    • Expanded security of information

    C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion :-

      A property in C# is a member of the class that provides a flexible mechanism to read, write or compute the data of a private field. Properties provide a level of abstraction so that we can change the value of the field while not affecting how they are used by a class.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free