Difference between a constructor with parameters and without parameters in c# - c#

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.

Related

Auto restrict runtime access to a property

Is it possible to have a class with unknown amount or types of properties, that will restrict the property access if needed, in runtime.
For example, if we have the following class:
public class SomeClass
{
public string SomeProperty { get; set; }
}
Then, accessing the class property outcome will depend on some runtime state, that is controllable by classes that are aggregated to it in some way.
A possible solution, would be to add some public boolean variable that can be set, then determain the behaviour by it.
For example:
public class SomeClass
{
public bool CanAccess { get; set; }
private string _someProperty;
public string SomeProperty
{
get
{
if (CanAccess)
{
return _someProperty;
}
throw new Exception();
}
set
{
if (CanAccess)
{
_someProperty = value;
}
throw new Exception();
}
}
}
This solution however, will require the class implementor to:
Do it right
Do it for all properties
I am not sure it is possible, but I want to implement that class in some way that will eliminate the need to check this "CanAccess" feild for every property.
This further means that if in the future I add some more properties to that class, they will also comply that "CanAccess" state automatically.
Thanks for helping.

Should I use a private property/field with a public getter method or directly use a public property for proper encapsulation?

For proper encapsulation, should I use a private property with a manual getter method like in Java:
public class Foo {
private int Prop { get; set; }
public Foo
{
Prop = 1;
}
public int GetProp()
{
return Prop;
}
}
Or should I simply use a public property?
public class Foo {
public int Prop { get; private set; }
public Foo
{
Prop = 1;
}
}
Properties are the way of creating getters and setters in C#, so there is no reason to create a getter method, like you would in Java.
In other words: You should use the second example.
Typically the proper way to do this is:
private int prop;
public int Prop
{
get { return prop; }
set { prop = value; } //do other stuff within set if needed.
}
This way you have access to everything, but can still do something custom (commonly NotifyPropertyChanged) if needed.
A property is just a syntactic sugar for get_PropertyName and set_PropertyName methods in c#.
public class Foo
{
public int Prop { get; private set; }
}
Is equivalent to:
public class Foo
{
private int _prop;
private void set_prop(int value) { _prop = value; }
public int get_prop() { return _prop; }
}
It's best that you use auto properties when possible and use properties with backing fields when you need to add logic to the getter/setter of individual fields.
If the property is going to be private, as it is in your first example, you should just use a field.
The point of a Property is usually that you have a get and set function, that can be used mostly like a variable. Your first example is really wierd - why not just make the getter only public? Readonly and Writeonly properties are not a uncommon sight:
//Public property with private get or writeonly
public int Prop { private get; set; }
//Readonyl property
public int Prop { get; private set; }
One important rule regarding the Backing field: It is very important that you do not mix up the Property and it's backing field, especially in class code. If you use Autoimplement Properties, that danger is non-existant. If your code is more complex than that, a common approach is to append a underscore (_) to the backing field name. Prop/prop is too easy to mix up. _Prop and Prop are really hard to mix up ,especialyl for autocompletion features.
In general, methods represent actions and properties represent data. While both your examples can be used identically, the 'proper' way of representing state is through properties, and using properties correctly tells consumers of your object that this is representing state, not an action.
You should also consider how things like serialization and intellisense are expecting properties instead of methods.

C# calling parent property while the child property is being called

I wanna see if there is anyway that when the child property method is being called, it will call the parent property as well.
Note that the child is generated by a code generator from edmx. So I can't change anything except adding a partial class for the child class. (It might be too trouble to change the generator.)
The situation I am having :
I have a class "MyClass" that is automatically generated from the database. I can't change anything on it except adding a partial class or change the code generator.
Now, I need to "do something" whenever the property Name is being called. I am thinking if I can put a parent there and make it call the parent to do "something" when the child property is "Name" is being called.
What I want :
public class ClassBase
{
public string Name
{
get
{
CallMethod();
return Name;
}
}
}
public class MyClass : ClassBase
{
public string Name { get; set; }
}
MyClass myClass = new MyClass();
myClass.Name; < -- this will call the parent as well.
Is there anyway to do it?
Thanks in advance
Not really related but since you're not strictly using automatic properties in ClassBase, you should create a private string variable for Name. Something like _name or whatever your internal coding standards dictate.
public class ClassBase
{
private string _name;
public virtual string Name
{
get
{
CallMethod();
return _name;
}
set
{
_name = value;
}
}
}
public class MyClass : ClassBase
{
//Pretty pointless really since you're not doing anything with MyClass.Name.
public new string Name
{
get
{
return base.Name;
}
set
{
base.Name = value;
}
}
MyClass myClass = new MyClass();
myClass.Name; <-- this will call the parent as well.
Based on "can't change base class" comment there is pretty much nothing you can do to make some code to be executed instead/before/after base class because your property/method will not be called when your new class used as base class (see sample in details part).
Potential solution : if you need to extend specially designed parital class's and it provides extension poinst like CallMethod is marked as partial - it is expected for implemnting portion of the class to implement it :
partial public class ClassBase
{
partial void CallMethod();
public string Name {get {CallMethod(); return "";}}
}
// in generated portion of "ClassBase"
partial public class ClassBase
{
partial void CallMethod() { /* do something here */ }
}
Answer to exact "how to call base class property" is to use base, but hiding property/method this way is confusing (see below):
new public string Name { get { return base.Name;} }
Note that you can't use automatic property in derived class case as you explicitly want some additional code to be executed. If you need set in derived class you need own backing field like:
private string derivedName;
new public string Name {
get { return base.Name + derivedName;}
set { derivedName = value;}
}
Details:
As said in comments hiding base class' properties/methods leads to very confusing behavior. For you case (slightly updated base class with baking field as original sample had infinite recursion):
public class ClassBase
{
private string name;
public string Name
{
get
{
CallMethod();
return name;
}
}
}
You can try to hide Name property in derived class:
public class MyClass : ClassBase
{
// notice "new" to show comiler you know what you doing
// otherwise you'll get warning (but behavior will be the same)
new public string Name { get; set; }
}
The issue with hiding is that base class' method is still easily callable and likely be called by mistake if using derived class as base class:
MyClass myDerved = new MyClass();
ClassBase myDervedAsBase = myDerved;
var name = myDerived.Name; // calls MyClass.Name
var name = myDerivedAsBase.Name; // calls ClassBase.Name
This can be solved by making base class' method/property virtual - but it requires change in base class:
public class ClassBase
{
virtual public string Name { get {... } }
}
public class MyClass : ClassBase
{
override public string Name { get { ... } }
}
If you need to call base class' method/property from derived class usebase.MethodName() like:
override public string Name { get
{
// do some new stuff here
var baseName = base.Name;
// maybe even change result
return baseName;
}
}
If you expect most derived classes to need such behavior it could be better to design base class explicitly to enforce such behavior. For example you can have property to call virtual method before/after computing the value to return like:
public class ClassBase
{
virtual protected string AboutToReturnName(string result)
{
return name;
}
public string Name
{
get
{
var result = "MyName";
return AboutToReturnName(result);
}
}
}
More ideas:
Alternative to virtual is partial methods which works when instead of deriving class is combined from many "partial" parts like ASP.Net pages - see Partial Classes and Methods
If you need notifications around change of property - consider implementing INotifyPropertyChange
if you need to know when properties/method are called in general - consider using interfaces and automatically generate wrapper classes that have pre/post callback. I.e. mocking frameworks (like EasyMoq or RhinoMock) and DI containers (like Unity) provide and use such functionality.
You cannot do it without modifying the code generator. The modification would have to generate a call base.Name.
You can override the property in your subclass with the new operator.
public class MyClass : ClassBase
{
public new string Name { get; set; }
}

C# new class clears base class values

I've searched extensively (though might have missed it). I've been doing so much web development that I can't seem to get this. I have a base case:
public class myfields
{
public String myfield1 { get; set; }
}
Then another class using this class:
class mydohere : myfields
{
public Boolean getValue {string xyz)
{
string abc = myfield1;
}
}
What I can't get it is, if I create:
mydohere Objmydohere = new mydohere();
The value of myfield1 is now null! All the values in base myfields are set to null (or empty since it is a new object). What is the best way to create fields (or parameters) in one class and share it among others without resetting their values? I've tried using keyword 'base'. I've tried using props and fields *since you can't instantiate them).
My goal is to to have a class of settable fields that I can use accross classes without making that class new for each class that is using it. Does this make sense? I'm sure there is a much better way to do this :)
It sounds like what you're looking for is a constant or static variable.
Use constant if it will always be the same:
const string myfield1 = "my const";
Use static if you'd like to set it once, maybe after doing some logic:
static string myfield1 = "my static";
This really depends on what you want to do with this "shared data" One way is to use a static class and dependency injection:
public interface Imyfields
{
String myfield1 { get; set; }
}
public class myfields : Imyfields
{
private static readonly Imyfields instance = new myfields();
private myfields()
{
}
public static Imyfields Instance
{
get
{
return instance;
}
}
public String myfield1 { get; set; }
}
class mydohere
{
private readonly Imyfields myfields;
public mydohere(Imyfields myfields)
{
this.myfields = myfields;
}
public Boolean getValue(string xyz)
{
string abc = this.myfields.myfield1;
}
}
Nothing is reset to null, it's never initialized with a value in the first time. In your base object, you only have a getter/setter, you don't have any code that initialize the value itself.
Maybe I don't understand the question well and others suggestion with static are what you really need! :)

Unsure when to use 'base' in C#

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.

Categories

Resources