Kamran Ahmed
Kamran Ahmed

Reputation: 12438

C# Indexers : Setting the value of a variable

public string name;
public int rollNo;

public string this[int i] 
{
    get 
    {
        switch(i)
        {
            case 0:
                return name;

            case 1:
                return rollNo.ToString();

            default:
                return "";
        }
    }
    set
    {
        switch (i)
        {
            case 0:
                name = value;
                break;
            case 1:
                rollNo = value;
                break;
        }
    }
}

above is the code that I'm trying to execute but the problem is rollNo = value shows this problem "Cannot convert from string to int". What I'd like to ask is, Does the value passed to the indexer need to be the same as the return type of indexer? If no please guide me what exactly I'm doing wrong. -Thanks

Upvotes: 1

Views: 228

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500575

Does the value passed to the indexer need to be the same as the return type of indexer?

Yes, it is by definition... just like the type of value in a property setter is also the same type as the property. You can't have an indexer or property which has one type for setting and a different type for getting. In your case you wouldn't want that anyway, as then you wouldn't be able to set name...

It's unclear why you're trying to use an indexer for this at all. It would be far clearer to just use two properties:

public string Name { get; set; }
public int RollNumber { get; set; }

That way no conversions are required at all. It's worth avoiding conversions unless you really need them.

(Additionally, your fields are already public, which is also a bad idea... fields are an implementation detail which should generally be hidden. Note that the automatically-implemented properties above mean you wouldn't even need to explicitly declare fields.)

Upvotes: 8

rossipedia
rossipedia

Reputation: 59377

value is going to be the type of the property, in your case string.

The simple solution would be to do:

rollNo = int.Parse(value);

Upvotes: 6

Related Questions