C# Property interface crash

so, i guess theres a gap in my understanding. When creating an interface, i have a few properties adn soem methods. The properties are set up like so

string myName { get; set; } // Property interface

then in a class that implements the interface, i define it like so:

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

however, when accessing the class member, (in some other file) unity crashes

	currentScript.init(numPlayers); //this works as intended
	currentScript.myName = "someName"; //this crashes unity, i have to restart it
        currentScript.changeMyName("someOtherName");//this also crashes unity!

what is causing the crash? what am i doing wrong?

1 Like

Could be wrong(it’s been a while), but shouldn’t it be:

public string MyName{
 //get set accessor code here
}

how is that different than what i have?

It’s capitalized.

Does it work if you use the auto getter/setter in the implementation?

That property is recursive.

myName.Get calls myName.Get, and so it’ll stack overflow. You need to name your underlying field and your property differently (or use autoimplemented properties). A common practice is lower case first letter for underlying field, capital first letter for property.

If you’re not going to use { get; set; } then you need a private member to act as the backing value.

public interface IThing {
    string Foo { get; set; }
}

public class Thing : IThing {
    private string foo;
    public string Foo
    {
        get { return foo; }
        set { foo = value; }
    }
}

Also - while capitalization is the correct pattern, it won’t affect functionality.

Right - my concern was Ntero’s statement - that it’s calling itself into a crash.

I see. i did something like this as a work around, but i had no idea i was on the right track. Anyway i get it now, thanks for the help everyone.

Just keep in mind that a Property is a distinct thing, and cannot be named the same as something else (function, variable, etc…). Also that properties don’t actually store anything, and are merely the accessors for somebody else.

If you just want a generically named backing field (because it’s only accessed via the property and the Get/Set doesn’t contain any logic to it) you can use autoimplemented properties:

public string MyName
{get; set;}

Will automatically fill in Get and Set with an auto named variable.