This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When do you use the “this” keyword?
Hello,
I understand that the This keyword is used to refer to an instance of the class, however, suppose I have a class called Life, which defines two fields, the person (their name) and their partner(their name):
class Life
{
//Fields
private string _person;
private string _partner;
//Properties
public string Person
{
get { return _person; }
set { _person = value; }
}
public string Partner
{
get { return _partner; }
set { _partner = value; }
}
//Constructor 1
public Life()
{
_person = "Dave";
_partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
//Constructor 2
public Life()
{
this._person = "Dave";
this._partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
Is there a difference between constructor 1 and constructor 2!?
Or is it just better coding practice to use the "This" keyword?
Regards
The constructors are the same. The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always use this when referring to instance variables and properties.
I no longer use the this keyword in this way after moving to a different company with different standards. I've gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).
My version of your class:
class Life
{
//Fields
private string person;
private string partner;
//Properties
public string Person
{
get { return this.person; }
set { this.person = value; }
}
public string Partner
{
get { return this.partner; }
set { this.partner = value; }
}
public Life()
{
this.person = "Dave";
this.partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
or, even better, but not as clear about the use of this with fields.
class Life
{
//Properties
public string Person { get; set; }
public string Partner { get; set; }
public Life()
{
this.Person = "Dave";
this.Partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
"this" is also used in .Net 3.5 with extension methods:
public static class MyExtensions
{
public static string Extend(this string text)
{
return text + " world";
}
}
would extend the string class
var text = "Hello";
text.Extend();
To answer your question: no, there is no difference in your two constructors. Imo, the "this" clutters the code and should only be used when necessary, e.g. when parameters and field variables have the same names.
There is also a case when the class explicitly implements an interface. If you need to call the interface methods from within your class you would have to cast this to the interface:
class Impl : IFace
{
public void DoStuff()
{
((IFace)this).SomeMethod();
}
void IFace.SomeMethod()
{
}
}
There is no difference in the two statements...
//These are exactly the same.
this._person
//and
_person
The reference to "this" is implied in the case of _person. I wouldn't say that it is necessarily "better" coding practice, I would say that it is just preference.
Already discussed
When do you use the "this" keyword?
Since you are using underscores, there is no conflict between the names; so the "this." is redundant and can be omitted. The IL will be unaffected.
As long as there is no ambiguity between a field and variable/parareter, there is only one scenario in which the this keyword (in the context of meaning the current instance - not ctor-chaining) is strictly necessary - invoking an extension method that is defined separately:
this.SomeExtensionMethod(); // works
SomeExtensionMethod(); // fails
Both constructors do the same thing anyway in the second one the this is redundant
You can use this to differentiate between a local variable named X and a class level field/property of the same name.
You shouldn't be using the private variables _person and _parter. That is the purpose of your getters and setters.
As far as the constructs, there is no real difference between them. That being said, I always prefer to use the This keyword as it lends towards readability.
Related
This question already has answers here:
Blocking access to private member variables? Force use of public properties?
(9 answers)
Closed 5 years ago.
Is there any way to enforce the rest of my class to access the property setter rather than the backing field? Consider the following clumsy code:
public class Brittle
{
private string _somethingWorthProtecting;
public string SomethingWorthProtecting
{
get { return _somethingWorthProtecting; }
set
{
_somethingWorthProtecting = value;
ReallyNeedToDoThisEverTimeTheValueChanges();
}
}
public void OhDearWhatWasIThinking()
{
_somethingWorthProtecting = "Shooting myself in the foot here, aren't I?";
}
}
As far as I know, C# does not provide any mechanism to prevent the class developer from making this mistake. (Auto-properties are clearly not an option in this situation.) Is there a design pattern or practice that can help safeguard against such inadvertant end-arounds?
you can move that logic to an abstract base class:
public abstract class Brittle
{
private string _somethingWorthProtecting;
public string SomethingWorthProtecting
{
get { return _somethingWorthProtecting; }
set
{
_somethingWorthProtecting = value;
ReallyNeedToDoThisEverTimeTheValueChanges();
}
}
//.....
}
then you can be sure no one will instantiate this class, and derived classes will not be able to access the private field.
public class BrittleDerived : Brittle
{
public void DoSomething()
{
// cannot access _somethingWorthProtecting;
}
}
In my class I have private variable, which I use inside the class only through get/set. Sometimes I forget, that I shouldn't use variable directly (even within the class) and must use get/set.
How to make that the only way to use a variable were get/set?
public class A {
int x;
public XVariable {
get { return x; }
set { x = value }
// some additional operations
}
void SomeMethod() {
x = 5; // no
XVariable = 5; // yes
}
}
C# has auto properties. No backing field needed in your code.
public class A {
public XVariable {
get;
set;
}
}
You can also have different access modifiers. Like if you want to only be able to set it from within the class.
public class A {
public XVariable {
get;
private set;
}
}
There won't be a backing field accessible from your code, but the compiler will generate one in the MSIL (what C# compiles to). You don't have to worry about that part though.
A potential downside Joe pointed out to auto props, sometimes you need to perform other actions (especially event handlers) in your property when you set something. But that's not possible with auto props. In that case, his answer would be more appropriate. But if that's not a concern for your use case, then my answer should be sufficient.
You can create a base class, and do all your real work in the derived class:
public class SomeBaseClass {
private int _x;
public int X { get { return _x; } set { _x = value; } }
}
public class DerivedClass : SomeBaseClass {
void DoSomething() {
// Does not have access to _x
}
}
Many people prefix their private variables with an underscore to help signify the variable is private. (Although it is a matter of opinion, some people like it and some don't) There is a bit more insight on this question.
You can however, scrap the field and use an auto property such as:
public XVariable { get; set; }
An auto property will store an anonymous backing field "out of view".
Is there an easy way to make an instance immutable?
Let's do an example, I have a class holding a lots of data fields (only data, no behavior):
class MyObject
{
// lots of fields painful to initialize all at once
// so we make fields mutable :
public String Title { get; set; }
public String Author { get; set; }
// ...
}
Example of creation:
MyObject CreationExample(String someParameters)
{
var obj = new MyObject
{
Title = "foo"
// lots of fields initialization
};
// even more fields initialization
obj.Author = "bar";
return obj;
}
But now that I have fully created my object, I don't want the object to be mutable anymore (because the data consumer will never need to change the state), so I would like something like that List.AsReadOnly:
var immutableObj = obj.AsReadOnly();
But if I want this behavior, I need to make another class that have exactly the same fields but without setter.
So is there any automatic way to generate this immutable class ? Or another way to allow mutability during creation but immutable once initialized ?
I know that fields can be marked as "readonly", but the object will be initialized outside of the class, and passing all fields as constructor parameters seems like a bad idea (too much parameters).
No, there is no easy way to make any type immutable, especially not if you want "deep" immutability (i.e. where no mutable object can be reached through the immutable object). You will have to explicitly design your types to be immutable. The usual mechanisms to make types immutable are these:
Declare (property-backing) fields readonly. (Or, starting with C# 6 / Visual Studio 2015, use read-only auto-implemented properties.)
Don't expose property setters, only getters.
In order to initialize (property-backing) fields, you must initialize them in the constructor. Therefore, pass the (property) values to the constructor.
Don't expose mutable objects, such as collections based on mutable-by-default types (like T[], List<T>, Dictionary<TKey,TValue>, etc.).
If you need to expose collections, either return them in a wrapper that prevents modification (e.g. .AsReadOnly()), or at the very least return a fresh copy of the internal collection.
Use the Builder pattern. The following example is too trivial to do the pattern justice, because it's usually recommended in cases where non-trivial object graphs need to be created; nevertheless, the basic idea is something like this:
class FooBuilder // mutable version used to prepare immutable objects
{
public int X { get; set; }
public List<string> Ys { get; set; }
public Foo Build()
{
return new Foo(x, ys);
}
}
class Foo // immutable version
{
public Foo(int x, List<string> ys)
{
this.x = x;
this.ys = new List<string>(ys); // create a copy, don't use the original
} // since that is beyond our control
private readonly int x;
private readonly List<string> ys;
…
}
Hmm I will enumerate my first thought on this...
1. Use internal setters if your only worry is manipulation outside of your assembly. internal will make your properties available to classes in the same assembly only. For example:
public class X
{
// ...
public int Field { get; internal set; }
// ...
}
2. I don't agree that it's necessarily a bad idea to have lots of parameters in your constructor.
3. You could generate another type at runtime that is a read-only version of your type. I can elaborate on this, but personally I think this is overkill.
Best, Iulian
As another solution you can use Dynamic Proxy. Alike approach was used for Entity Framework http://blogs.msdn.com/b/adonet/archive/2009/12/22/poco-proxies-part-1.aspx. Here is example how you can do it using Castle.DynamicProxy framework. This code is based on original example from Castle Dynamic proxy (http://kozmic.net/2008/12/16/castle-dynamicproxy-tutorial-part-i-introduction/)
namespace ConsoleApplication8
{
using System;
using Castle.DynamicProxy;
internal interface IFreezable
{
bool IsFrozen { get; }
void Freeze();
}
public class Pet : IFreezable
{
public virtual string Name { get; set; }
public virtual int Age { get; set; }
public virtual bool Deceased { get; set; }
bool _isForzen;
public bool IsFrozen => this._isForzen;
public void Freeze()
{
this._isForzen = true;
}
public override string ToString()
{
return string.Format("Name: {0}, Age: {1}, Deceased: {2}", Name, Age, Deceased);
}
}
[Serializable]
public class FreezableObjectInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
IFreezable obj = (IFreezable)invocation.InvocationTarget;
if (obj.IsFrozen && invocation.Method.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
{
throw new NotSupportedException("Target is frozen");
}
invocation.Proceed();
}
}
public static class FreezableObjectFactory
{
private static readonly ProxyGenerator _generator = new ProxyGenerator(new PersistentProxyBuilder());
public static TFreezable CreateInstance<TFreezable>() where TFreezable : class, new()
{
var freezableInterceptor = new FreezableObjectInterceptor();
var proxy = _generator.CreateClassProxy<TFreezable>(freezableInterceptor);
return proxy;
}
}
class Program
{
static void Main(string[] args)
{
var rex = FreezableObjectFactory.CreateInstance<Pet>();
rex.Name = "Rex";
Console.WriteLine(rex.ToString());
Console.WriteLine("Add 50 years");
rex.Age += 50;
Console.WriteLine("Age: {0}", rex.Age);
rex.Deceased = true;
Console.WriteLine("Deceased: {0}", rex.Deceased);
rex.Freeze();
try
{
rex.Age++;
}
catch (Exception ex)
{
Console.WriteLine("Oups. Can't change that anymore");
}
Console.WriteLine("--- press enter to close");
Console.ReadLine();
}
}
}
I would suggest having an abstract base type ReadableMyObject along with derived types MutableMyObject and ImmutableMyObject. Have constructors for all the types accept a ReadableMyObject, and have all the property setters for ReadableMyObject call an abstract ThrowIfNotMutable method before updating their backing field. Additionally, have ReadableMyObject support a public abstract AsImmutable() method.
Although this approach will require writing some boilerplate for each property of your object, that will be the extent of the required code duplication. The constructors for MutableMyObject and ImmutableMyObject will simply pass the received object to the base-class constructor. Class MutableMyObject should implement ThrowIfNotMutable to do nothing, and AsImmutable() to return new ImmutableMyObject(this);. Class ImmutableByObject should implement ThrowIfNotMutable to throw an exception, and AsImmutable() to return this;.
Code which receives a ReadableMyObject and wants to persist its contents should call its AsImmutable() method and store the resulting ImmutableMyObject. Code which receives a ReadableMyObject and wants a slightly-modified version should call new MutableMyObject(theObject) and then modify that as required.
You kind of hinted at a way in your question, but I'm not sure if this is not an option for you:
class MyObject
{
// lots of fields painful to initialize all at once
// so we make fields mutable :
public String Title { get; protected set; }
public String Author { get; protected set; }
// ...
public MyObject(string title, string author)
{
this.Title = title;
this.Author = author;
}
}
Due to the constructor being the only way of manipulating your Author and Title, the class is in effect immutable after construction.
EDIT:
as stakx mentioned, I too am a big fan of using builders - especially because it makes unit testing easier. For the above class you could have a builder such as:
public class MyObjectBuilder
{
private string _author = "Default Author";
private string _title = "Default title";
public MyObjectBuilder WithAuthor(string author)
{
this._author = author;
return this;
}
public MyObjectBuilder WithTitle(string title)
{
this._title = title;
return this;
}
public MyObject Build()
{
return new MyObject(_title, _author);
}
}
This way you can construct your objects with default values, or override them as you please, but MyObject's properties can't be changed after construction.
// Returns a MyObject with "Default Author", "Default Title"
MyObject obj1 = new MyObjectBuilder.Build();
// Returns a MyObject with "George R. R. Martin", "Default Title"
MyObject obj2 = new MyObjectBuilder
.WithAuthor("George R. R. Martin")
.Build();
If you ever need to add new properties to your class, it's much easier to go back to your unit tests that consume from a builder rather than from a hardcoded object instantiation (i don't know what to call it, so pardon my terms).
Well, if you have too many parameters and you dont want to do constructors with parameters....here is an option
class MyObject
{
private string _title;
private string _author;
public MyObject()
{
}
public String Title
{
get
{
return _title;
}
set
{
if (String.IsNullOrWhiteSpace(_title))
{
_title = value;
}
}
}
public String Author
{
get
{
return _author;
}
set
{
if (String.IsNullOrWhiteSpace(_author))
{
_author = value;
}
}
}
// ...
}
Here's another option. Declare a base class with protected members and a derived class that redefines the members such that they are public.
public abstract class MyClass
{
public string Title { get; protected set; }
public string Author { get; protected set; }
public class Mutable : MyClass
{
public new string Title { get { return base.Title; } set { base.Title = value; } }
public new string Author { get { return base.Author; } set { base.Author = value; } }
}
}
Creating code will use the derived class.
MyClass immutableInstance = new MyClass.Mutable { Title = "Foo", "Author" = "Your Mom" };
But for all cases where immutability is expected, use the base class:
void DoSomething(MyClass immutableInstance) { ... }
In Java, it's possible to have methods inside an enum.
Is there such possibility in C# or is it just a string collection and that's it?
I tried to override ToString() but it does not compile. Does someone have a simple code sample?
You can write extension methods for enum types:
enum Stuff
{
Thing1,
Thing2
}
static class StuffMethods
{
public static String GetString(this Stuff s1)
{
switch (s1)
{
case Stuff.Thing1:
return "Yeah!";
case Stuff.Thing2:
return "Okay!";
default:
return "What?!";
}
}
}
class Program
{
static void Main(string[] args)
{
Stuff thing = Stuff.Thing1;
String str = thing.GetString();
}
}
You can write an extension method for your enum:
How to: Create a New Method for an Enumeration (C# Programming Guide)
Another option is to use the Enumeration Class created by Jimmy Bogard.
Basically, you must create a class that inherits from his Enumeration. Example:
public class EmployeeType : Enumeration
{
public static readonly EmployeeType Manager
= new EmployeeType(0, "Manager");
public static readonly EmployeeType Servant
= new EmployeeType(1, "Servant");
public static readonly EmployeeType Assistant
= new EmployeeType(2, "Assistant to the Regional Manager");
private EmployeeType() { }
private EmployeeType(int value, string displayName) : base(value, displayName) { }
// Your method...
public override string ToString()
{
return $"{value} - {displayName}!";
}
}
Then you can use it like an enum, with the possibility to put methods inside it (among another things):
EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager
You can download it with NuGet.
Although this implementation is not native in the language, the syntax (construction and usage) is pretty close to languages that implement enums natively better than C# (Kotlin for example).
Nope. You can create a class, then add a bunch of properties to the class to somewhat emulate an enum, but thats not really the same thing.
class MyClass
{
public string MyString1 { get{ return "one";} }
public string MyString2 { get{ return "two";} }
public string MyString3 { get{ return "three";} }
public void MyMethod()
{
// do something.
}
}
A better pattern would be to put your methods in a class separate from your emum.
Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:
static class EnumExtensions {
public static T GetEnum<T>(this string itemName) {
return (T) Enum.Parse(typeof(T), itemName, true);
}
}
This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety.
Hopefully it helps someone
C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.
Use of classes is highly discouraged by Microsoft in this case, use (data)struct(ures) instead; The STRUCT is intended as a light class for data and its handlers and can handle functions just fine. C# and its compiler don't have the tracking and efficiency capabilities as one knows from JAVA, where the more times a certain class / method is used the faster it runs and its use becomes 'anticipated'. C# simply doesn't have that, so to differentiate, use STRUCT instead of CLASS.
I have a class that has private fields... (cars)
I then inherit from this class... (Audi)
In the (Audi) class, when I type this. in the constructor...
the private fields are not available...
Do I need to do anything special to expose this private fields in (cars) class so that they are accessible via this. in (Audi class)?
One (bad) option is to make the fields protected - but don't do this; it still breaks proper encapsulation. Two good options:
make the setter protected
provide a constructor that accepts the values
examples:
public string Name { get; protected set; }
(C# 2.0)
private string name;
public string Name {
get { return name; }
protected set { name = value; }
}
or:
class BaseType {
private string name;
public BaseType(string name) {
this.name = name;
}
}
class DerivedType : BaseType {
public DerivedType() : base("Foo") {}
}
Philippe's suggestion to declare the fields as protected instead of private will indeed work - but I suggest you don't do it anyway.
Why should a derived class care about an implementation detail of how the data is stored? I suggest you expose protected properties which are (currently) backed by those fields, instead of exposing the fields themselves.
I treat the API you expose to derived classes as very similar to the API you expose to other types - it should be a higher level of abstraction than implementation details which you may want to change later.
You should declare them as "protected" instead of private
You are probably looking for a concept called constructor inheritance. You can forward arguments to the base classes constructor - see this example, where the Audi has a flag indicating whether it's an S-Line edition or not:
namespace ConstructorInheritance
{
abstract class Car
{
private int horsePower;
private int maximumSpeed;
public Car(int horsePower, int maximumSpeed)
{
this.horsePower = horsePower;
this.maximumSpeed = maximumSpeed;
}
}
class Audi : Car
{
private bool isSLineEdition = false;
// note, how the base constructor is called _and_ the S-Line variable is set in Audi's constructor!
public Audi(bool isSLineEdition, int horsePower, int maximumSpeed)
: base(horsePower, maximumSpeed)
{
this.isSLineEdition = isSLineEdition;
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Audi(true, 210, 255);
// break here and watch the car instance in the debugger...
}
} }