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?

  • 4
    `testStar.starName = "star1";` – Ňɏssa Pøngjǣrdenlarp Sep 04 '16 at 18:48
  • 1
    Coming from Java? – Steve Sep 04 '16 at 18:55
  • 1
    [Using properties in C#](https://msdn.microsoft.com/en-us/library/w86s7x04.aspx) on MSDN is a good starting point to learn about properties, but since recommendations to read documentation are rarely helpful I believe [duplicate](http://stackoverflow.com/questions/5096926/what-is-the-get-set-syntax-in-c) (which describes syntax, meaning and usage of `get`/`set`) covers this question just fine. – Alexei Levenkov Sep 04 '16 at 18:57

1 Answers1

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.

FranzHuber23
  • 3,311
  • 5
  • 24
  • 63
  • I know, this code doesn't make sense, but just as example... – FranzHuber23 Sep 04 '16 at 18:53
  • 1
    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) – Alexei Levenkov Sep 04 '16 at 19:01