What is C# code doing: - c#

In the following code:
public class A
{
public A():this(null){}
public A(string b){/*code here*/}
}
What is the use of first constructor?

The first constructor is passing null into parameter b of the second constructor.
Thus if you call new A() it will be the same as calling new A(null)

When you have a constructor with a parameter
public A(string b){ /* code here */ }
public A():this("") { } //default
the default constructor actually calls the "parameter constructor" with "" as a parameter. You are passing a parameter. This is done in order to avoid writing the same code twice

It's a constructor overload.
I agree it doesn't seem to be very useful in this case because most likely the uninitialised value for a string is null anyway.
See also Constructors in C#

this happens when you're overloading constructors.
in your example the empty contructor public A():this(null){} looks for a constructor that can take in an object value of null. since a string is an object that can take nulls, it calls that constructor.
this example seems very simplistic.
a more meaningful example (but still keeping it basic):
public class AddNumbers
{
public AddNumbers():this(100, 100)
{ }
public AddNumbers(int x, int y)
{
int sum = x + y;
Console.WriteLine(sum.ToString());
}
}
in this example, when a calling program calls the empty constructor, it will output 200. because it is calling the AddNumbers method with x = 100, y = 100.
i know it's a simple example but i hope that makes it clearer.

It's a default constructor that calls second with b==null.

Some interfaces or designers require there to be a "parameterless" constructor.
This method comes in handy in those times.

Having a parameterless default constructor is required when object initialization is used:
Employee e = new Employee() {FirstName="John", LastName="Smith"};
In this case, I probably would not use constructor chaining, though. Constructor overloading gives you an alternative way to initialize with parameters. Where constructor chaining is really useful is in making constructor parameters optional; C# doesn't support optional parameters (yet).
"Best practice" will depend on the situation, usage, architecture, requirements, etc. (ISO Consulting Rule Number One: "It depends.")

Related

Generic class with overridden method - which gets called?

I have a class that overrides the addition operator twice. One that takes the type parameter and one that takes a double:
public class A<T>
{
public A() { }
public static A<T> operator +(A<T> a, T t)
{
Console.WriteLine("Generic add called.");
return new A<T>(); // return to keep the compiler happy
}
public static A<T> operator +(A<T> a, double d)
{
Console.WriteLine("Double add called.");
return new A<T>(); // return to keep the compiler happy
}
}
When the class is parameterized by the int type, it behaves as expected:
A<int> aInt = new A<int>();
var test = aInt + 3;
// -> Generic add called.
test = aInt + 3.0;
// -> Double add called.
But when parameterized by the double type, the non-generic add is called:
A<double> aDouble = new A<double>();
var otherTest = aDouble + 3.0;
// -> Double add called.
Assuming this behavior is the norm, I know which will be called. The non-generic override will be preferred. That said...
Will the non-generic method be always be preferred in the event of a collision?
All of the above code is available, runnable in your browser, here
EDIT: This question is related, but it's asking about generic methods, not classes. He gives this code:
class A
{
public static void MyMethod<T>(T myVal) { }
public static void MyMethod(int myVal) { }
}
which does not apply to my usage examples. Distinguishing between a.MyMethod(3) and a.MyMethod<int>(3) is obvious - one is generic and one is not.
The more specific method will be chosen, but that construction is a bad idea because it is technically unspecified behaviour.
To quote #EricLippert, substituting the code snippets for the ones from my question:
But the situation with [aDouble + 3.0] is far worse. The CLR rules make this sort of situation "implementation defined behaviour" and therefore any old thing can happen. Technically, the CLR could refuse to verify a program that constructs type [A<double>]. Or it could crash. In point of fact it does neither; it does the best it can with the bad situation.
Are there any examples of this sort of type construction causing truly implementation-defined behaviour?
Yes. See these articles for details:
http://blogs.msdn.com/b/ericlippert/archive/2006/04/05/odious-ambiguous-overloads-part-one.aspx
http://blogs.msdn.com/b/ericlippert/archive/2006/04/06/odious-ambiguous-overloads-part-two.aspx
Simple answering yes. The compiler assume that because you have treated by hand a particular type parameter, that means that it has some special logic for you. That's why the second operator is called. To say further, operators are nothing more than static methods that accepts some parameters. For your case it's a binary operator so the static method has two parameters.

Is it possible to restrict the values of optional parameters in C#?

C# allows the use of optional parameters: one can specify the value in case the parameter is omitted in a call and the compiler then specifies the value itself.
Example:
public interface IFoo {
void SomeMethod (int para = 0);
}
This idea is useful but a problem is that one can define several "default values" on different levels of the class hierarchy. Example:
public class SubFoo : IFoo {
public void SomeMethod (int para = 1) {
//do something
}
}
If one later calls:
SubFoo sf = new SubFoo ();
sf.SomeMethod ();
Foo f = sf;
f.SomeMethod ();
The result is that the first call is done with para equal to 1 and the second with para equal to 0 (as interface). This make sense since the compiler adds the default values and in the first case the this is a SubFoo thus the default value is 1.
It is of course up to the programmer to maintain consistency, but such schizophrenic situations can easily occur when a programmer changes his/her mind in the middle of the process and forgets to modify all default values.
Problematic is that the compiler doesn't warn that different default values are in use whereas this can be checked by moving up the class hierarchy. Furthmore some people might mimic default parameters with:
public class SubFoo2 {
public virtual void SomeMethod () {
SomeMethod(1);
}
public void SomeMethod (int para) {
//do something
}
}
Which allows dynamic binding and thus overriding consistently. It thus requires one to be very careful with how default values are "implemented".
Are there ways to enforce (with compiler flags for instance) to check whether the default values are consistent? If not it would be nice to have at least a warning that something is not really consistent.
Well not necessary compile-time solution - but you can make unit test for that (I suspect that you're taking seriously unit testing and you run them frequently if you ask this kind of question). The idea is to create assertion method like AssertThatDefaultParametersAreEqual(Type forType) - find all classes that are not abstract (using reflection) and inherit from forType then iterate over all methods which have defined default parameters:
MethodInfo[] methodInfo = Type.GetType(classType).GetMethods(BindingFlags.OptionalParamBinding | BindingFlags.Invoke);
Group them by MethodInfo.Name and check does within the group all same parameters with default values (could be obtained by MethodInfo.GetParameters().Where(x => x.IsOptional)) have the equal property of ParameterInfo.DefaultValue.
edit: btw. that might not work in Mono because compilers aren't obligated to emit for instance: Optional BindingFlag.
If you want to have a compile time indication that a method is changing the default value of an optional argument, you're going to need to use some sort of 3rd party code analysis tool, as C# itself doesn't provide any means of providing such a restriction, or any warnings when its done.
As a workaround, one option is to avoid using optional parameter values and instead use multiple overloads. Since you have an interface here, that would mean using an extension method so that the implementation of the overload with a default value is still defined in the general case:
public interface IFoo
{
void SomeMethod(int para);
}
public static class FooExtensions
{
public static void SomeMethod(this IFoo foo)
{
foo.SomeMethod(0);
}
}
So while this approach does technically still allow someone to create an extension (or instance) method named SomeMethod and accepting no int argument, it would mean that someone would really need to go out of their way to actively change the "default value". It doesn't require implementations of the interface to supply the default value, which risks them unintentionally providing the wrong default value.
Define const int DefaultPara = 1; and then use that instead of hard coding numerical values.
interface IFoo
{
void SomeMethod (int para = DefaultPara);
}
public class SubFoo : IFoo {
public void SomeMethod (int para = DefaultPara) {
//do something
}
}

`this` and a class constructor

I currently have a class and I am a bit confused with its constructor .
public class BarListTracker : GotTickIndicator
{
public BarListTracker(BarInterval interval) : this(new BarInterval[] { interval }) { }
}
what does the statement this(new BarInterval[] { interval }) imply ?
This is constructor chaining. Essentially, you're calling a different constructor before executing the contents of that constructor.
public class Foo
{
public Foo()
: this("Hello")
{
Console.Write(" World!");
}
public Foo(string text)
{
Console.Write(text);
}
}
new Foo(); //outputs "Hello World!"
So somewhere in your BarListTracker there should be another constructor that takes either a BarInterval[] array or an IEnumerable<BarInterval> like this:
public class BarListTracker : GotTickIndicator
{
public BarListTracker(BarInterval interval)
: this(new BarInterval[] { interval })
{
//specific initialization for this constructor
}
public BarListTracker(BarInterval[] intervals)
{
//shared initialization logic for both constructors
}
}
It will execute the body BarListTracker(BarInterval[]), then execute the body of BarListTracker(BarInterval)
This is generally used to reduce code duplication. If you had some initialization code for your BarListTracker, it makes more sense to write it in one place and share that logic with your constructors rather than rewriting it for each one.
In addition, it lets you pass in or modify the input parameters with basic expressions. So in this case, in-line with calling the BarListTracker(BarInterval[]) constructor, it's wrapping the single BarInterval interval object as an array to match the signature. Likely this is just a convenience overload to provide a simpler API for programmers who may often have only a single BarInterval to construct the tracker with.
This means a call of another constructor of the BarListTracker that takes an array of BarInterval objects, passing in an array containing the object passed into this constructor. It makes the call
var tracker = new BarListTracker(interval);
equivalent to this:
var tracker = new BarListTracker(new BarInterval[] { interval });
That is indicating that they are basing, or calling, another constructor in the class when this one gets called and passing the value as an array of BarInterval. In this case it's not a base class because otherwise it would say : base(...), it's another constructor defined in this very same class.
This is very common because you want to access a class a number of different ways, and in this case, it appears they wanted to be able to send just a single object at times without setting up an array in the code.
However, one thing they could have done is just changed the other constructor, the one being called with : this to be this:
public BarListTracker(params BarInterval[] interval)
and they wouldn't have even needed the second constructor. It's a cleaner solution and yields the same results everywhere. The other constructor still gets an array, you can even pass an array to it if you wanted:
var arrOfBarInterval = new BarInterval[] { val1, val2 };
var tracker = new BarListTracker(arrOfBarInterval);
But, you can also just pass one:
var tracker = new BarListTracker(barInterval);
If you have the ability to do that I would recommend it.
One caveat to note, the : this(...) constructor gets called and executed before the constructor you're in. Keep that in mind when building logic.
Call another constructor in this class, something like this:
public BarListTracker(BarInterval[] intervals)
It calls another constructor of the same class for example
public class Point{
public Point(int x, int y){
this.x=x;
this.y=y;
}
public Point():this(0,0){}
}
if in your code you call
var p= new Point();
you will use the parameterless constructor defined which will call the constructor with parameter passing to him 0,0
this is pretty usefull if you have more than one constructor which accept a lot of parameter and want to provide simpler constructor with default parameter
you will have another constructor that takes array of BarInterval as parameter . This is basically nothing but calling a constructor from another constructor . Another link that might be helpful is Call one constructor from another

How to call an extension method from own class without casting?

I'm trying to call an extension method on my own class, but it fails to compile. Consider the following lines of code:
public interface IHelloWorld
{
}
public static class Extensions
{
public static string HelloWorld(this IHelloWorld ext)
{
return "Hello world!";
}
}
public class Test : IHelloWorld
{
public string SaySomething()
{
return HelloWorld();
}
}
Basically I'm extending on the interface. I keep getting this error:
The name 'HelloWorld' does not exist in the current context
Can anybody explains this to me? When I do a cast all seems well:
return ((Test)this).HelloWorld();
Any explanations?
The cast isn't necessary - the this part is. So this works fine:
return this.HelloWorld();
Section 7.6.5.2 explicitly talks about method invocations of the form
expr.identifier ( )
expr.identifier ( args )
expr.identifier < typeargs > ( )
expr.identifier < typeargs > ( args )
This invocation:
HelloWorld()
isn't of that form, as there's no expression involved.
It's not immediately clear to me why the language was designed that way (i.e. why the "implicit this" was excluded) and maybe Eric Lippert will add an answer to that effect later. (The answer may well be along the lines of "because it would have taken a long time to spec, implement and test, for relatively little benefit.") However, this answer at least shows that the C# compiler is sticking to the spec...
this.HelloWorld(); works with no casting.
Remember how Extension methods work:
You use an object and compiler would know the type then it could resolve it to the extension method. If no object is used, then it would not be able to resolve it.
Not really an answer, but too long to fit in the comment section...
Let's take the following example, that I think is pretty common:
public class DoubleSet : List<double>
{
public IEnumerable<double> Square()
{
return this.Select( x => x*x );
}
}
It is a perfectly valid point that the this is not necessary for the compiler to interpret the Select method properly.
However I think that in some ways, imposing the dot notation highlights the fact that we're dealing with an extension method, and that as such, the extension method will only access the members of the current instance through public accessors, even if you're calling it within the private scope of the class.
It makes explicit to the code reader that the extension method will treat the "this" instance as if it didn't know anything of its internal state. And indeed the class of the object is completely unknown to the extension method (as the extension method only knows the interface)
If the code was only:
public IEnumerable<double> Square()
{
return Select( x => x*x );
}
it would be much less obvious that you're dealing with IEnumerable.Select that is actually calling the IList.GetEnumerator and getting every element one by one to call the x => x*x function.

Statements only in methods, but what about declarations?

On MSDN I found:
In C#, every executed instruction is done so in the context of a method.
But I also read that an int A=5; statement can be in the class body. It seems it's not in a method body, so why this is possible? It is probably just term confusion but I would like to know.
Adrian is correct. To clarify further: "int A = 5;" is only a statement when it is inside a method body. When it is outside a method body then it is a field declaration with an initializer, which is logically moved into the constructor body.
The exact semantics of how the initializers work is a bit tricky. For some thoughts on that, see:
http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx
http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx
class Example
{
int A = 5;
}
is equal to
class Example
{
int A;
public Example()
{
A = 5;
}
}
So the assignment is still part of a method (the constructor).
You are probably referring to field initializations:
class Foo
{
private static int i = 5;
}
Even this instruction runs inside the context of a method. In this particular case it is the static constructor. If the field is not static then it will be the normal constructor.

Categories

Resources