To "this" or not to "this" in C#? [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
When do you use the “this” keyword?
Best practices for using the ‘this’ keyword in C#
I have a style question regarding the this keyword. Do you use this when self-referencing auto-implemented properties or methods within a class for the sake of clarity?
For one example, in your Constructor, do you write your parameter assignments as:
public class Foo
{
public string FooProperty { get; set; }
public Foo(string fooProperty)
{
this.FooProperty = fooProperty;
}
...
}
OR as:
public class Foo
{
public string FooProperty { get; set; }
public Foo(string fooProperty)
{
FooProperty = fooProperty;
}
...
}

IMHO, the this is a very useful keyword. Once I see the "this", I know it is a class variable. Otherwise, I would have to check whether its a parameter, a variable declared within the method. "This" saves time :) (ambiguous joke hehe)

Related

C# What does : this() mean after a constructor of struct [duplicate]

This question already has answers here:
what is 'this' constructor, what is it for
(4 answers)
Closed 6 years ago.
Could you answer, what does : this() mean after a constructor of struct?
public struct BaseProject
{
public BaseProject(string project)
: this()
{
this.Project = project;
}
public string Project { get; private set; }
}
What does : this() mean after a constructor of struct?
The this keyword in C# refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.
As it pertains to a struct and the constructor of a struct, it actually is meaningless and does nothing. In C# a struct doesn't have a parameterless constructor. They are very similar to class constructors but differ in the following ways:
Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
A struct cannot have an initializer in the form: base (argument-list).
As such, the : this() after the struct constructor does nothing and is redundant - it can be removed with no issues whatsoever. However, in the context of a struct constructor, the this keyword works as expected.
Classes
When used in after a constructor, it invokes another constructor in the same class first - in this specific situation the parameterless constructor. This can be used to initialize other various parts of an object instance as they are invoked first.
Constructors
Read "using constructors" on MSDN for more details.
Consider the following:
public class FooBar
{
public int Number { get; }
public string Name { get; }
public FooBar()
{
Number = 10;
Name = "Pickles";
}
public FooBar(int number) : this()
{
Number = number;
}
public FooBar(int number, string name) : this(number)
{
Name = name;
}
}
var fooBar1 = new FooBar();
var fooBar2 = new FooBar(20);
var fooBar3 = new FooBar(77, "Stackoverflow");
// The following would be true
// fooBar1.Number == 10 and fooBar1.Name == "Pickles"
// fooBar2.Number == 20 and fooBar2.Name == "Pickles"
// fooBar3.Number == 77 and fooBar2.Name == "Stackoverflow"
The this keyword in the context of a constructor can also be used (as shown above) to call into parameterized constructors as well. If you were to inherit then you could call into default or parameterized constructors of the base class using the base keyword.
A constructor can invoke another constructor in the same object by
using the this keyword.
From Using Constructors (C# Programming Guide)
So in your example, when the constructor that takes a string is called, the parameterless constructor is (implicitly) called first, followed by the method body of the constructor that takes a string being executed.
It means it's calling the parameterless constructor of the type.

Interface With Class Enums [duplicate]

This question already has answers here:
Enum "Inheritance"
(17 answers)
Closed 7 years ago.
Is there a way to interface with or inherit the enum of another class? Obviously I can move the enum outside of the class, but I am curious if a reference can be made:
public class deferment
{
public enum test
{
test = 0,
live
}
}
public class defermentLog
{
public enum test1 : deferment:test //this is where I want to reference
{
}
public test1 action()
{
return test1.live;
}
}
In that case, yes, you can.
namespace ConsoleTests
{
using TestAlias = Class1.test;
public class Class1
{
public enum test
{
test,
live
}
}
public class Class2
{
public void x()
{
TestAlias t = TestAlias.live;
}
}
}
Its called a type alias, and its defined like this: using TestAlias= Class1.test;
It should be noted though that you have to define that alias in the file that you use it and it does not copy over to other files, so you have to define it in every one you use it.

Initialize string properties to String.Empty [duplicate]

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.

C# constructor using this [duplicate]

This question already has answers here:
Call one constructor from another
(13 answers)
Closed 9 years ago.
Can somebody explain what means : this(123) in a constructor ?
public class MyObject
{
public MyObject(): this(123)
{
}
............
}
Because your class has another constructor which takes and int as parameter.
public class MyObject
{
public MyObject()
: this(123)
{
}
public MyObject(int x) //something like this
{
}
}
See: Using Constructors (C# Programming Guide)
A constructor can invoke another constructor in the same object by
using the this keyword.
This means, that you are calling another constructor with the fixed Value "123":
public class MyObject
{
public MyObject(): this(123)
{
}
public MyObject(int number)
{
}
}
Means: Whenever you call new MyObject(), without any parameter, it equals the call to new MyObject(123);
this is used to call one constructor from another within the same class.
Refer to this article for better understanding.
http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C
You have another constructor that accepts an int (thought it could be long or double, or anything else that int can implicitly cast to)
public class MyObject
{
public MyObject(): this(123)
{
}
public MyObject(int num)
{
//do something with the num
}
}
That means "before you execute what between the curly brackets, execute the suitable Constructor with parameters 123"
The syntax provided is used for "constructor chaining" whereby the specified constructor (which accepts an integer argument) is called before the body of the current constructor.

Do you use the "this" operator in C#? [duplicate]

This question already has answers here:
Closed 14 years ago.
Duplicate post, see: When do you use the "this" keyword?
On almost every project I worked the "This" operator is used, when i start developing i was told that it is a good practice. is this really necessary does it gives you more readability?
Tools like Resharper have a built in hint saying "redundant qualifier," but I disagree with it and quickly disable the rule.
I always use the this qualifier because it lets me know at a glance whether or not the reference is a property/field, or a static class ref for example:
public class MyClass {
public int Foo { get; set; }
}
public MyClass MyRef { get; }
or
public static class MyRef {
public static int Foo { get; set; }
}
so:
void method() {
MyRef.Foo = 4; // might be either
}
void method() {
this.MyRef.Foo = 4; // definitely property/field
}
Just my 2c.
-Oisin

Categories

Resources