0

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?

2
  • 1
    You need to declare constructor with string as argument, e.g. public aclass(string value) { athing = value; } before using aclass thing = new aclass("somestring");. Commented Sep 27, 2018 at 4:52
  • 2
    Actually I understand the question. Unfortunately C# does not have atom object as Erlang. Commented Sep 27, 2018 at 4:59

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.