QuestionC
QuestionC

Reputation: 10064

How do I combine `var` and `const`?

Short Version

In C++ I could do this...

const auto & help_id = help_type.functionHelpTypeId;

How can I do that in C#?


Long Version

How can I make one variable be a readonly alias for a class field or property in C#?

I have a method where I am making read-only aliases at the top of my function in order to make the rest of the code a little clearer and save some typing later.

        var help_id = help_type.functionHelpTypeId;
        var changeset_version = changeset.version;
        var helpPageType = help_type.helpPageType;
        // &ct.

My problem is that since these are not const, anyone could reassign them or mutate the objects they're referring to, which is not my intention. In order to know that these are just readonly aliases for class fields, one would basically have to study the whole function, which isn't ok.

Upvotes: 1

Views: 156

Answers (2)

Xiaoy312
Xiaoy312

Reputation: 14477

To complement @AlexeiLenkov's answer, you can still create a anonymous type whose properties are readonly:

var help = new
{
    help_id = help_type.functionHelpTypeId,
    changeset_version = changeset.version,
    helpPageType = help_type.helpPageType,
};

help.help_id = 312; // CS0200: It is readonly

However, this can only be used within local scope. Also, take note that reference types are mutable, and help itself is also a reference type.

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

You can't: "Implicitly-typed local variables cannot be constant".

Just use explicit type for const.

More discussion: Type-inferring a constant in C#

Upvotes: 2

Related Questions