This question already has answers here:
What is the best way to give a C# auto-property an initial value?
(23 answers)
Closed 8 years ago.
I'm used to writing classes like this:
public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?
public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.
Something like this would make more sense to me:
public string Bar { get; set; } = "bar";
Update - the answer below was written before C# 6 came along. In C# 6 you can write:
public class Foo
{
public string Bar { get; set; } = "bar";
}
You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):
public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)
Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.
This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.
You can do it via the constructor of your class:
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.
This will be possible in C# 6.0:
public int Y { get; } = 2;
In the default constructor (and any non-default ones if you have any too of course):
public foo() {
Bar = "bar";
}
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.
Related
This question might look very simple for many, but I really want to understand the following
Difference between the two classes along with the Name property
Benefits of using one among the two
When & Where to use such (any practical applications)?
Code:
public class test1
{
public test1()
{
}
public string Name { get; set; }
}
public class test2
{
public test2(string name)
{
Name = name;
}
public string Name { get; set; }
}
public class SampleTest
{
public void PerformTests()
{
test1 Test1 = new test1();
Test1.Name = "Power Measurements";
test2 Test2 = new test2("Power Measurements");
}
}
to be more precise please consider the objects Test1 & Test2.
any help on this would be much appreciated.
The physical difference between the two classes is only in the constructor. One has a parameter; one doesn't.
The semantic difference is that test2 requires a Name. In test1, it is optional. So you would use test2 if you want to force a caller to provide a name.
Constructors with parameters force the developer to supply any required variables when creating and instance of the object.
For example, lets say each object should have a 'Name' but it cant be changed after the object is created.
public class TestClass
{
private string _name = string.Empty;
public string Name
{
get{ return _name; }
private set { _name = value; }
}
public TestClass(string name)
{
this.Name = name;
}
}
The constructor with no parameters is default, you can use it to create an object without any further specification, using a parameter you can specify a name or something else during the creation of the object. You should probably read more about the basics of object oriented programming to get a better understanding.
When your property is ment to be read-writable there might be no difference on both. It depends on if it is required property or optional one. When you define a constructor you force the property to be provided. In the other case your property might or might not be set by the user of your class. You may however provide a default-value for it within your constructor in this case.
However often you won´t need to have a writable property thus you can make it read-only (by declaring a private setter e.g.) and set its value within the constructor. In this case you have to provide the value within the constructors parameter.
public class TestClass
{
public string Name { get; private set; }
public TestClass(string name)
{
this.Name = name;
}
}
Now you may set the value of the property by providing it within the constructor. Once it has been set it is immutable (at least outside the scope of the class). However you may change the value inside the class. If you want to avoid this also you have to provide a readonly-backing-field for the property.
public class TestClass
{
private readonly _name;
public string Name { get { return this._name; } }
public TestClass(string name)
{
this._name = name;
}
}
This is the safest appraoch to avoid that the value you initlally provided within the constructor is ever changed either by a user of your class or within the class itself.
When I was in university 6-8 years ago, I learned that it was common practise to have public get and set methods but private variables when using Java. However these days, when I use C#, I realise that a lot of the common class variables have public accessibility, e.g. String.Length.
Is it common practise in C# to make variables public (so is it widely accepted that people can program in such a manner)?
Thanks
String.Length isn't really a public variable. In C#, it's common to use getters this way:
class Foo
{
private int _bar;
public int Bar
{
get { return _bar; } // getter
set { _bar = value; } // setter
}
}
// ...
Foo foo = new Foo();
foo.Bar = 42;
In other words, string.Length is only a getter for the read only variable string._lengh.
Often, it's also a good practice to mark the setter as private meaning that only the where your setter is declared can set the value for your property, and any other derived class can access it with the getter method.
So there are a couple of ways to declare properties with:
Use the prop shortcut and hit Tab twice (Code Snippets in Visual Studio). This produces:
public int Foo{ get; set; }
Use the propg shortcut + Tab twice to declare the setter as private. Looks like this:
public int Foo{ get; private set; }
Use the full implementation in using the shortcut propfull which will give you:
private int Foo;
public int MyProperty
{
get { return Foo;}
set { Foo = value;}
}
You can also make a public variable readonly, instead of making its setter private:
class Foo
{
public readonly int Bar; // Bar can only be initialized in the constructor
public Foo()
{
this.Bar = 42;
}
}
I am making a save/load system for a big game project in C#.
Each class that has to be saved implements a method DoSnapshot().
Inside the method, the programmer must make a call to a function for every field in the class - either DoSnapshot(foo) if foo should be saved, or Ignore(foo) if it should not.
I have a DoSnapshot method for many primitive types like DoFloat, DoString as well as versions for complex types.
I have 100s of classes and the project is still being developed.
Is it possible to add some kind of verification that all of the fields in each class are either used in a Snapshot() or an Ignore() call? Omitting fields would cause bugs.
The verification could either be runtime, or compile-time. I only want to use it during development, it will not be released to users.
You could add an attribute to the fields that need to be saved, and then loop over every property in your class in the DoSnapshot method. When the property has the attribute you're looking for, you call Snapshot, otherwise you call Ignore.
public class SomeClass : SomeBaseClass
{
[Required]
public string Foo { get; set; }
public string Bar { get; set; }
public override void DoSnapshot()
{
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
var isRequired = property.GetCustomAttributes(typeof (RequiredAttribute), false).Length > 0;
if (isRequired)
{
// Something
}
else
{
// SomethingElse
}
}
}
}
What i would do is create an attribute and "tag" each field if it should be saved or not. Then, at runtime, i would query the class using reflection to get all fields which should be serialized:
public class RandomClass
{
public string Foo { get; set; }
[Ignore]
public int Bar { get; set; }
}
public class IgnoreAttribute : Attribute
{
}
class Program
{
static void Main(string[] args)
{
var properties = typeof(RandomClass).GetProperties()
.Where(prop => !prop.IsDefined(typeof(IgnoreAttribute), false));
// Serialize all values
}
}
I'm trying to teach myself about OOP in C#, but I have a question about when to use base. I understand the general principles, but I'm not sure what's best in the example below. This simple test includes:
An interface with two string properties
An abstract class that implements this interface and adds a couple more string properties
Two classes that implement the abstract class. One uses base and the other doesn't, but they both produce the same output when the program is executed.
My question is: in this example, is one implementation more desirable than the other? I'm not really sure if there are any meaningful differences between TranslationStyleA and TranslationStyleB, or if it's just down to personal preference?
Many thanks for your time and thoughts!
using System;
namespace Test
{
interface ITranslation
{
string English { get; set; }
string French { get; set; }
}
public abstract class Translation : ITranslation
{
public virtual string English { get; set; }
public virtual string French { get; set; }
public string EnglishToFrench { get { return English + " is " + French + " in French"; } }
public string FrenchToEnglish { get { return French + " is " + English + " in English"; } }
public Translation(string e, string f)
{
English = e;
French = f;
}
}
public class TranslationStyleA : Translation
{
public override string English
{
get { return base.English; }
set { base.English = value; }
}
public override string French
{
get { return base.French; }
set { base.French = value; }
}
public TranslationStyleA(string e, string f) : base(e, f)
{
}
}
public class TranslationStyleB : Translation
{
private string english;
public override string English
{
get { return english; }
set { english = value; }
}
private string french;
public override string French
{
get { return french; }
set { french = value; }
}
public TranslationStyleB(string e, string f) : base(e, f)
{
this.English = e;
this.French = f;
}
}
class Program
{
static void Main(string[] args)
{
TranslationStyleA a = new TranslationStyleA("cheese", "fromage");
Console.WriteLine("Test A:");
Console.WriteLine(a.EnglishToFrench);
Console.WriteLine(a.FrenchToEnglish);
TranslationStyleB b = new TranslationStyleB("cheese", "fromage");
Console.WriteLine("Test B:");
Console.WriteLine(b.EnglishToFrench);
Console.WriteLine(b.FrenchToEnglish);
Console.ReadKey();
}
}
}
The first thing that you need to understand is what's going on when you have an automatic property:
public virtual string English { get; set; }
Behind the scenes, the compiler is generating a private field, and getting/setting that private field when you access the property. It is equivalent to this
private string _english;
public virtual string English { get { return _english; } set { _english = value; } }
except that you don't know the name of the private field, and so you cannot access it.
So in your TranslationStyleA class, you are not actually doing anything with the English property, because it just accesses the base class's property directly and doesn't change it's behavior.
// None of this is even needed- we are just delegating to the base class
public override string English
{
get { return base.English; }
set { base.English = value; }
}
Now in the TranslationStyleB class, you are actually changing the behavior of the property (albeit in a fairly useless way). Instead of storing the value for the English property in the base class's auto-implemented private variable, you are storing it in the private variable defined at the derived class level:
private string english;
public override string English
{
get { return english; }
set { english = value; }
}
Neither of these implementations does anything of course, and as implemented neither is needed, since the base class implements the properties perfectly fine itself. So my answer to your original question is that neither is preferred, given the code as you describe it.
Now, let's look at an example where your question is relevant. You only need to override them if you want to change their behavior, for instance.
// We don't want any leading or trailing whitespace, so we remove it here.
public override string English
{
get { return base.English; }
set { base.English = value.Trim(); }
}
We want to delegate to the base class here, because of why these were properties in the first place. Semantically, a property is the same as a field:
public String Foo;
public String Foo { get; set; } // <-- why bother with all this extra { get; set; } stuff?
The reason is that from the compiler's perspective, it is a breaking change in an interface to go from a property to a field. So if I change
public String Foo;
to
public String Foo { get; set; }
Then any code that depends on my code needs to be recompiled. However, if I change
public String Foo { get; set; }
to
private string _foo;
public String Foo { get { return _foo; } set { _foo = value.Trim(); } }
then dependent code still only sees the public property, and does not need recompilation (because the interface of my class has not changed).
If the base class here (Translation) were to change it's behavior for the property English thus:
private string _english;
public String English { get { return _english; } set { _english = value.ToUpper(); } }
the you would want to pick that up in your derived classes!
So considering that properties have behavior associated with them, you should always delegate to the parent class implementation unless that implementation has undesirable effects in your deriving class.
The first style is definitely preferable unless you have some good reason to pick the other one.
The automatically-implemented properties of Translation each add a field, and style B adds more rather than using the ones the compiler added. Style A reuses the one the compiler added, saving some storage.
Additionally, there's no need to override the superclass's properties if you're not going to change their functionality. You could even write another style like this:
public class TranslationStyleC : Translation {
public TranslationStyleC(string e, string f) : base(e, f) {
}
}
You don't really need to override any of the superclass properties to achieve the effect that you intend, since you don't enhance the superclass behavior in any way.
If you remove the abstract modifier from the base Translation, you don't need the subclasses anymore, since it will be functionally equivalent to both.
Now, as to when to use base; you should use it when you want to access functionality in the superclass that's been overridden in the subclass. base calls are always statically bound to the superclass method at compile time; even if the superclass method is virtual (as in your case). For a curious thing that can happen with base calls take a look here.
As mentioned before, style A reuses the fields already declared whereas style B declares new fields. Regarding your question about when to use base, the rule of thumb would be "whenever you would like to reuse logic/code defined in the parent class".
It does come down to how you intend to leverage your constructs.
As implemented, the overridden members on TranslationStyleA are a bit redundant as the consumer could just as easily access the base members without providing the overrides in the base derivation. In cases such as these I personally won't bother overriding the base members at all if doing so doesn't add any value to design.
The second implementation is common when you truly want to override the setting and accessing of base class members, for instance, if the setting of a base class member is the catalyst for initiating another operation then the overriden member on the derivation would be an appropriate place for that to occur.
I wanted to know what is a good option to solve this issue ,
I have a class that expose an enum : (this is just an example)
public class Foo
{
public State FooState { get; private set; }
public string SomeData { get; set; }
public Foo(State state)
{
FooState = state;
}
public Foo()
{
}
public enum State
{
None,
Bad,
Good
}
}
in one use of the class the user can adjust the state, and on the other he can't so the state is set on NONE and that good but i dont want the user to have the possibility of setting it to None. i Know that there isnt an internal enum field obviously, is there any way it can be done else, bare in mine that the Foo class cant be changed due to specification.
Clarification
The meaning of the class can not be change is that the design and purpose of the class can not change, not the class itself.
The state of the class is only in use when the c'tor get a value. i cant use two classes or use interface due to reflection use in the future. (i just cant use typeof)
I believe you can do this by providing two interfaces with different access level, implement them explicitly and instead of Foo type use one of the interfaces either for read-only or full access.
Since Foo can not be changed you can use Wrapper approach:
Foo foo = new Foo(State.Good);
FooWrapper fooWrapper = new FooWrapper(foo);
// would be read-write
(FooWrapper as IReaonlyState).State
// would be readonly
(FooWrapper as IWritableState).State
public interface IReadonlyState
{
State FooState { get; }
}
public interface IWritableState
{
State FooState { get; set; }
}
public class FooWrapper : IReadonlyState, IWritableState
{
Foo foo;
public FooWrapper(Foo foo)
{
this.foo = foo;
}
State IReadonlyState.FooState
{
get
{
return this.foo.FooState;
}
}
State IWritableState.FooState
{
get
{
return this.foo.FooState;
}
set
{
this.foo.FooState = value;
}
}
}
So, you want the consumer to be able to set both State=Bad and State=Good.
But if State==None you should be able to read, but not change it. Sounds like you need to implement the setter explicitly.