Ze Indie Gamer
Ze Indie Gamer

Reputation: 23

string created from variable in c#

Is it possible to to define a string from a variable where the string does NOT have quotations. Example:

public class aclass
{
    public string athing;
}

public void example(string thing)
{
    aclass thing = new aclass();
}

The string thing can't be put into aclass thing = new aclass(); normaly. Is there anyway to do it?

Upvotes: 0

Views: 104

Answers (3)

Michał Turczyn
Michał Turczyn

Reputation: 37337

You have to ways of setting fields/property value of an object.

First is to do it through the constructor, as mentioned in other answer.

Second can be implmeneted in various ways:

  1. Expose public property making field privte:

    public class aclass
    {
        private string _athing;
        public string Athing 
        {
                get { return _athing; }
                set { _athing = value; }
        }
    }
    
    public void example(string thing)
    {
        aclass aclass = new aclass();
        aclass.Athing = thing;
    }
    

Or even shorter, you could use property:

public class aclass
{
    public string Athing {get; set; }
}
  1. Using your implementation, you make your field public, so you can set it easily:

    public void example(string thing)
    {
        aclass aclass = new aclass();
        aclass.athing = thing;
    }
    

But it doesn't comply with OOP encapsulation principle.

Upvotes: 0

Rajdip Khavad
Rajdip Khavad

Reputation: 317

You can do it this using many way but generally standard way is using constructor please refer this link for better understanding.

C# : assign data to properties via constructor vs. instantiating

Upvotes: 0

Aydin
Aydin

Reputation: 15284

You need a constructor

void Main()
{
    CreateExampleObject("testing");
}

public class Example
{
    // This is a constructor that requires a string as an argument
    public Example(string text)
    {
        this.Text = text;
    }

    public string Text { get; set; }
}

public void CreateExampleObject(string text)
{
    Example example = new Example(text);

    Console.WriteLine(example.Text);
}

Upvotes: 2

Related Questions