CdrTomalak
CdrTomalak

Reputation: 479

c# update attribute via reference or method

Bit of a noob question but:

I have a custom class defined as:

public class Icon
{
    string name;
int value;
public void setName(string nameIn)
{
    name = nameIn;
}
public void setValue(int valueIn)
{
    value = valueIn;
}
}

Is it better to update the object attributes (in this case from an array of type Icon) from another class in the same application domain using:

fm.iconData[0].setName("Plum");

OR is it better to set by changing my instance variable modifiers in the Icon class to 'public' and use:

fm.iconData[0].name = "Plum";

Is this breaking any OO design concepts?

Upvotes: 1

Views: 490

Answers (3)

markmuetz
markmuetz

Reputation: 9664

As everyone else has said, this should be a property. If you plan on adding extra logic to the property (e.g. validation, raising events), you can define the property like this:

public class Icon
{
    string name;
    public string Name
    {
        get { return name; }
        set
        {
            // custom logic can go here...
            name = value; // value is whatever has been set to this property
        }
    }
}

name is only visible in the class as it is private. Name is visible externally.

Upvotes: 0

Maciej
Maciej

Reputation: 7961

Name is a clear example of a simple property. Make it a property (not a public field) and assign a value to it:

fm.iconData[0].Name = "Plum";

Have this property defined like this:

public string Name {get;set;}

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160892

Neither. In this case use a property instead of a public field or explicit setter/getter methods:

public class Icon
{
    public string Name {get;set;}
}

Properties are compiled down to setter/getter methods which allows you to change your internal implementation later on if required so still respects encapsulation. Explicit setter/getter methods are not idiomatic for C#.

Also see MSDN on properties.

Upvotes: 2

Related Questions