Home > Mobile >  How to access the Private member in the same class using getter and setter property in C#
How to access the Private member in the same class using getter and setter property in C#

Time:03-24

In the given code. I want to access the private value in the other main class I read the value from the console and through this class want to display in the console

using System;

class Customer
{
    private string _customerAddress;

    public string CustomerAddress
    {
        get { return this._customerAddress; }   
        set { this._customerAddress = value; }
    }
    public void DisplayDetails()
    {
        Console.WriteLine("Hello World", CustomerAddress);
    }
}

CodePudding user response:

I'm not sure what you mean, but if you want to give '_customerAddress' a value in your main form and then display the value with the 'DisplayDetails()' method then the following might help.

Main Form ==> make an Customer object and then give _customerAddress a value by simple doing this:

Customer customer = new Customer();
customer.CustomerAddress = "test";
customer.DisplayDetails();

You should also consider to give '_customerAddress' as a parameter in the constructor.

In case you want to acces a private field from another class and display it in this class, then you should do the following:

Step1: make a property in the other class like you did in the Customer class.

Step 2: Make a another Display function and give to its parameter the object of the other class.

public class OtherClass
{
  private string message;

  public string Message
  {
     get{return this.message;}
     set{this.message = value;}
  }
}

call the property in your Customer Class:

class Customer
{
    private string _customerAddress;

    public string CustomerAddress
    {
        get { return this._customerAddress; }   
        set { this._customerAddress = value; }
    }
    public void DisplayDetails()
    {
        Console.WriteLine("Hello World", CustomerAddress);
    }
    
    public void DisplayMessage(OtherClass otherClass) 
    {
        Console.WriteLine("Hello World",otherClass.Message);
    }
}

You can also make the method dat displays the message in the OtherClass Class and call that method in your Customer Class.

  • Related