Why Static keyword before the function signature [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why must C# operator overloads be static?
Why Static keyword before the function signature of all the overloaded operators in C# like:
public static void operator = (Object a, Object b)
When we are doing a = b; then a value will be implicitly passed right. So there is no need of static keyword. It must be like:
public void operator = (Object b)
Is it?

The fact that operators are static allows them to be used in situations where there are null values. It also emphasizes the fact that operators are not applied polymorphically. (They potentially could be applied polymorphically if they weren't static, admittedly... but overriding would generally be a bad idea anyway IMO.)
(Note that you can't overload the assignment operator in C# anyway.)

Otherwise you would Always need an instance of the Object to perform that. Which you might not have on case a or b is null.

Related

Why in C# we can't evaluate methods in ternary operator? [duplicate]

This question already has answers here:
Why doesn't the C# ternary operator work with delegates?
(2 answers)
Closed 3 years ago.
I'm trying execute next code, but in C# it doesn't allowed. Why?
In C++ it works just fine..
void A()
{
Console.WriteLine("A");
}
void B()
{
Console.WriteLine("B");
}
void C()
{
//getRandomInt return digit from 0 to 99
bool compareResult= getRandomInt(100) < 50;
var result = compareResult ? A : B;
result();
}
The error message is telling you there's "no implicit conversion between method group and method group". In the immemorial tradition of compiler errors, this has virtually no meaning in any known natural language. With experience, however, we learn that it's telling us we need to cast to something else, and we also know from experience that C# is difficult with us about implicit casts of references to methods unless the reference is typed as Action or Func. This is a crude and empirical rule of thumb which I find helps me get on with my life very quickly when I run into these things. There's value in a full and proper understanding of why this is the way it is; see below for some insights into that.
A and B are nonary methods returning void, so I tried casting to Action. It compiled.
var result = compareResult ? (Action)A : B;
The estimable Eric Lippert (see his entire series of comments below) clarifies:
...method groups do not have a type in C#; they are convertible to certain types, but they do not have a type
And when we say "method" group, we mean something like "referring to a function by name without calling it". Consider:
public void A() { }
public int A(int x) => 2 * x;
public void B() { }
There's more than one A. The compiler might be able to resolve the ambiguity on its own by taking the one that looks like B, if any of them do, but it doesn't, and from experience, I there are good reasons why it doesn't try to do that, which Eric addresses:
the short version is: solving that problem is too much work for too little gain, and we're too likely to get it wrong. The slightly longer version is: we decided that in C# the only way to resolve a method group is to evaluate the member of the group for their fitness with respect to a set of arguments, either in the form of expressions when the method group is called, or in the form of types when the method group is converted to a delegate. There are no arguments available in this example!
But when you include a cast to (Action) as you suggested, suddenly there are arguments available, namely, an empty argument list. Now we have evidence for which method in the group that the developer would like to choose: the one which has no arguments.

Implicit C# Conversion For Generic Wrapper Class

I'm writing a generic wrapper class to implement INotifyPropertyChanged for a bunch of properties within another one of my classes. I've been doing some research on the implicit conversion operator, but I'm a bit confused on how to use it within a generic class. Essentially I would like to get the internally wrapped value without needing to explicitly call the internal property. The behavior I am looking for is essentially how the Nullable<T> class/struct works where if the internal value is not null, then it will return the internally wrapped value directly. Example below:
//current behavior
MyWrapperClass<int> wrapped = new MyWrapperClass();
int startCount = wrapped.Data;
//behavior I am looking to implement
int startCount = wrapped
In the second example above wrapped will return it's internally wrapped value instead of type T instead of having to call the inner property. This is how Nullable<T> behaves.
When looking into implicit conversions it appeared that I needed to know the type before hand per this MSDN article: Using Conversion Operators
Do I need to convert on a dynamic type since the type is not known? Example:
public static implicit operator dynamic(MyWrapperClass w)
Or can I perform implicit conversion on type T as seen below? This would prevent me from making the method static, which I noticed is used in all the sample code I've seen involving both implicit and explicit conversion operators. This option seems "wrong" to me, but I could not find much information on the subject here.
public implicit operator T(MyWrapperClass w)
EDIT: This SO Question might cause this to be labeled as a dupe, but the accepted answer is not what I am looking for since they say to use the property which I am already doing.
After some testing it appears that the second option works without issue and still allows itself to be static. I used #AndersForsgren's answer to this question (not accepted answer) to figure this out. Apparently I misunderstood how the implicit operator overload works. The code snippet that corrects this is as follows:
public static implicit operator T(WrapperClass<T> input)
{
return input.Data;
}

Is Operator Overriding supported by C#

I have gone to an interview where I was asked to answer a question:
Is operator overriding supported by C#?
I know that operator overloading is supported but I have no idea about overriding a operator. Is it possible?
No, operator overriding is not supported. The term Overriding is used when a method is inherited by a subclass and the subclass overrides it with its own implementation. Operators are all static in C# and cannot be overridden.
Overloading means that another method with the same name but a different signature (arguments) is defined. That's what you can do with operators.
This is extremely important to know when writing operators in C#. The operator is bound at compile time. The effective type which is passed to the operator at runtime is not important at all.
Eg. you write some comparison operator
public static bool operator==(MyClass c1, MyClass c2)
{
//...
}
And have the following code:
object myObj1 = new MyClass();
object myObj2 = new MyClass();
if (myObj1 == myObj2)
//...
object's operator will be called, not your own, because the
arguments are references of type object.

Difference between String1.Equals(string2) and string1==string2 C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C#: String.Equals vs. ==
Are string.Equals() and == operator really same?
sometimes in a condition between two strings, I write:
if(string1==string2) //Do something
and sometimes I write:
if(string1.Equals(string2)) //Do something
The problem is sometimes the first one doesn't work, or miswork, is there any difference between the two expressions?
The first one will always work so long as the compile-time type of both operands is string.
If the compile-time type of either operand is anything other than string, it will use the normal reference identity comparison, rather than comparing strings for equality. Basically you want to call the ==(string, string) overload instead of the normal ==(object, object) overload.
Note that the first will succeed even if string1 is null, whereas the second will throw NullReferenceException in that case. An alternative in order to preserve the Equals call but avoiding this problem is to call the static object.Equals(object, object) method:
if (object.Equals(string1, string2))
Personally I'd just use == in cases where the compile-time types are appropriate though.
The use of == on two string types will perform a reference identity check, meaning it will only return true if both references point to the same object. Equals on the other hand is expected to perform a value comparison, and will return true if the references point to objects that are equivalent.

What is the difference between .Equals and == [duplicate]

This question already has answers here:
C# difference between == and Equals()
(20 answers)
Closed 9 years ago.
What is the difference between a.Equals(b) and a == b for value types, reference types, and strings? It would seem as though a == b works just fine for strings, but I'm trying to be sure to use good coding practices.
From When should I use Equals and when should I use ==:
The Equals method is just a virtual
one defined in System.Object, and
overridden by whichever classes choose
to do so. The == operator is an
operator which can be overloaded by
classes, but which usually has
identity behaviour.
For reference types where == has not
been overloaded, it compares whether
two references refer to the same
object - which is exactly what the
implementation of Equals does in
System.Object.
Value types do not provide an overload
for == by default. However, most of
the value types provided by the
framework provide their own overload.
The default implementation of Equals
for a value type is provided by
ValueType, and uses reflection to make
the comparison, which makes it
significantly slower than a
type-specific implementation normally
would be. This implementation also
calls Equals on pairs of references
within the two values being compared.
using System;
public class Test
{
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;
Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}
The result of this short sample program is
True
True
False
True
Here is a great blog post about WHY the implementations are different.
Essentially == is going to be bound at compile time using the types of the variables and .Equals is going to be dynamically bound at runtime.
In the most shorthand answer:
== opertator is to check identity. (i.e: a==b are these two are the same object?)
.Equals() is to check value. (i.e: a.Equals(b) are both holding identical values?)
With one exception:
For string and predefined value types (such as int, float etc..),
the operator == will answer for value and not identity. (same as using .Equals())
One significant difference between them is that == is a static binary operator that works on two instances of a type whereas Equals is an instance method. The reason this matters is that you can do this:
Foo foo = new Foo()
Foo foo2 = null;
foo2 == foo;
But you cannot do this without throwing a NullReferenceException:
Foo foo = new Foo()
Foo foo2 = null;
foo2.Equals(foo);
At a simple level, the difference is which method is called. The == method will attempt ot bind to operator== if defined for the types in question. If no == is found for value types it will do a value comparison and for reference types it will do a reference comparison. A .Equals call will do a virtual dispatch on the .Equals method.
As to what the particular methods do, it's all in the code. Users can define / override these methods and do anything they please. Ideally this methods should be equivalent (sorry for the pun) and have the same output but it is not always the case.
One simple way to help remember the difference is that a.Equals(b) is more analogous to
a == (object)b.
The .Equals() method is not generic and accepts an argument of type "object", and so when comparing to the == operator you have to think about it as if the right-hand operand were cast to object first.
One implication is that a.Equals(b) will nearly always return some value for a and b, regardless of type (the normal way to overload is to just return false if b is an unkown type). a == b will just throw an exception if there's no comparison available for those types.
"==" is an operator that can be overloaded to perform different things based on the types being compared.
The default operation performed by "==" is a.Equals(b);
Here's how you could overload this operator for string types:
public static bool operator == (string str1, string str2)
{
return (str1.Length == str2.Length;)
}
Note that this is different than str1.Equals(str2);
Derived classes can also override and redefine Equals().
As far as "best practices" go, it depends on your intent.
For strings you want to be careful of culture specific comparisons. The classic example is the german double S, that looks a bit like a b. This should match with "ss" but doesn't in a simple == comparison.
For string comparisons that are culture sensitive use: String.Compare(expected, value, StringComparison....) == 0 ? with the StringComparison overload you need.
By default, both == and .Equals() are equivalent apart from the possibility of calling .Equals() on a null instance (which would give you a NullReferenceException). You can, however, override the functionality of either of them independently (though I'm not sure that would ever be a good idea unless you're trying to work around the shortcomings of another system), which would mean you could MAKE them different.
You'll find people on both sides of the aisle as to the one to use. I prefer the operator rather than the function.
If you're talking about strings, though, it's likely a better idea to use string.Compare() instead of either one of those options.

Categories