0

I am trying to set a variable in a class that I created.

public class Star
{
    public int       starID         { get; set; }
    public Vector3   position       { get; set; }
    public string    starName       { get; set; }
    public char      starClass      { get; set; }

}

Later, in the same file I tried the following code:

public void generateGalaxy()
{
    for(int i = 0; i < numOfStars; i++)
    {
        spawnStar();
    }
}

public void spawnStar()
{
    Star testStar = new Star();

    testStar.starName.set("star1");
}

The error was on '.set', the message was:

'string' does not contain a definition for 'set' and no extension method 'set' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?

Any ideas?

3
  • 4
    testStar.starName = "star1"; Commented Sep 4, 2016 at 18:48
  • 1
    Coming from Java? Commented Sep 4, 2016 at 18:55
  • 1
    Using properties in C# on MSDN is a good starting point to learn about properties, but since recommendations to read documentation are rarely helpful I believe duplicate (which describes syntax, meaning and usage of get/set) covers this question just fine. Commented Sep 4, 2016 at 18:57

1 Answer 1

0

I would suggest:

public void generateGalaxy()
{
    for(int i = 0; i < numOfStars; i++)
    {
        Star testStar = spawnStar();
    }
}

public Star spawnStar()
{
    return new Star(){starName="star1"}; //Using object initializer and anonymous class
}

As Alexei said: It's another possibility to do so.

@Sean McKenna: testStar.starName.set("star1"); // You don't need to specify the "set" explicitly. Just use testStar.starName = "star1";.

And another thing: I would recommend to work according to the Microsoft C# Coding Conventions or Internal Coding Guidelines. This means renaming the properties in your class like this:

public class Star
{
    public int       StarID         { get; set; }
    public Vector3   Position       { get; set; }
    public string    StarName       { get; set; }
    public char      StarClass      { get; set; }
}

According to the example provided in the guidlines:

public class Foo
{
   int bar;

   public int Bar
   {
      get { return bar; }
      set { bar = value; }
   }
}

As you don't necessarily need a backing field, you can also use my simplified version as provided above.

Sign up to request clarification or add additional context in comments.

2 Comments

I know, this code doesn't make sense, but just as example...
I would suggest to explain code you are posting for future answers. Unless your goal is to confuse OP this does not answer question at all (also indeed gives alternative to exact code OP provided in the post)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.