I have a .Net C# class where I need to make a variable public. I need to initialize this variable within a method (not within the constructor). However, I don't want the variable to be modifieable by other classes. Is this possible?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Are you not allowed to use a property for this? If you are:
Necro for sure, but this bares mentioning with the improvements to the language in 6.0
Sure. Make it a property, and make the setter private:
Then to set it (from within some method in the class):
Use a private variable and expose a public property.
The answers so far work good as long as you dont use reference types. Otherwise you will still be able to manipulate the internals of that variable. e.g:
This will result in the console output:Which may be exactly what you want as you wont be able to change SomeBar but if you want to make the internals of the variable unmodifiable you need to pass back a copy of the variable, e.g.:
which will result in the output:See comments for why I added the third example:
Don't use a field - use a property:
In this example
Foo.Bar
is readable everywhere and writable only by members ofFoo
itself.As a side note, this example is using a C# feature introduced in version 3 called automatically implemented properties. This is syntactical sugar that the compiler will transform into a regular property that has a private backing field like this: