What if property is declared as private? How to call it in C#?

Viewed 71

My question is simple: if a property is declared as private - how to call it?

In java we use getter&setter in which variable is private but in C# property is public; if I make it private, then in main class, it can't be called.

This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace staticProperty
{
    class Class1
    {
        private string name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace staticProperty
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            c1.????
        }
    }
}
3 Answers

You can follow the same layout as Java with

class Class1
{
    private string _name;

    public string getName(){
        return _name;
    }

    //methods to set the private variable anywhere in here.
}

Or more concise

class Class1
{
   public string Name{ get; private set; }
}

The getter will be public in both cases, but setting will be private.

You can use reflection to call private property in a class.

I write the following code example, and you could have a look.

 class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            PropertyInfo property = stu.GetType().GetProperty("Name", BindingFlags.Instance | BindingFlags.NonPublic);
            property.SetValue(stu,"test1");   //set value
            string value = property.GetValue(stu).ToString();//get value
            Console.WriteLine(value);
            Console.ReadKey();
        }

    }
    public class Student
    {
        private string Name { get; set; }
    }

Output:

enter image description here

private string name;

public string _name
{
    get { return name; }
    set { name = value; }
}

So I understand property is like getter setter and it should be public.

Question is that if i make public property direct without variable than it should be public and treated as public class or outer class

Related