How do you call this language construct / technique in C#? - c#

I am reading a C# code from some one else, and I found this line:
RE-EDITED: (It was missing the sprite object and one extra parameter)
Foo1.move(sprite, new Vector3(1.7f, 1.7f, 1.7f), 5f).setColor(myRGB);
The method .setColor() is not part of Foo1 class, it is from another class, so my question is regarding how is possible to call this method at the end of the method .move()?
The Foo1 class has this declaration:
public class Foo1 : MonoBehaviour {...}
and the class that contains the .setColor() method has this declaration:
public class ObjectProperties {...}
Is this technique usual in C#? and how is it called?

setColor could be an extension method, see https://msdn.microsoft.com/en-us//library/bb383977.aspx or move() is just returning an object that has a setColor method. Sometimes called fluent interface.

Assumption
In order to answer this question (I should not have withdrawed my close vote!!! The question lacks essential information) I assume the following:
public class Foo1{
Foo1 move(...);
}
public class ObjectProperties{
static Foo1/void setColor(this Foo1); //magic explained later
}
The name of the second class suggests this set up
Answer
It is called Extension Methods, which is just synctactic sugar for static helper method
An extension method allows a third-party developer to add a methods to a class developed by someone else without the need to use inheritance.
Your clever coworker found a way to move a Foo1 on the screen which was not written by the original developer. Instead of pleasing the developer to add the new function to the class (with all the IP/patent issues and by having to wait for next release), your coworker did all this in house.
He wrote
public static class ObjectProperties {
public static [something] setColor(this Foo1 foo, Object rgb){
}
}
The above, with the exception of the this modifier to be discussed, is a legal static helper method that can be used in older C# version and Java and any other OO language. It can access Foo's public members and so on.
What makes C# cool is that you will be able to call this method like if it was a real method of Foo1, thus extending the class with a new method
It's all sugar, baby
Don't be fooled. There is no magic, there is no hacking, there is no Jon Skeet refactoring the obfuscated DLL from which Foo1 comes.
The compiler will just translate your call to
ObjectProperties.move(Foo1.move(sprite, new Vector3(1.7f, 1.7f, 1.7f), 5f),myRgb);
Nothing else

Find out what Foo1.move() returns. It should return a class that has the setColor method as #Servy said.

Related

Why can't I call an extension method from a base class of the extended type‏?

I'm trying add the ability to lookup elements in a List<KeyValuePair<string,int>> by overriding the indexer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class MyList : List<KeyValuePair<string, int>>
{
public int this[string key]
{
get
{
return base.Single(item => item.Key == key).Value;
}
}
}
}
For some reason, the compiler is throwing this error:
'System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'Single'.
While it is true that List<T> doesn't have that method, it should be visible because it is an extension method from the System.Linq namespace (which is included). Obviously using this.Single resolves the issue, but why is access via base an error?
Section 7.6.8 of the C# spec says
When base.I occurs in a class or struct, I must denote a member of the base class of that class or struct.
Which might seem to preclude access to extension method via base. However it also says
At binding-time, base-access expressions of the form base.I and base[E] are evaluated exactly as if they were written ((B)this).I and ((B)this)[E], where B is the base class of the class or struct in which the construct occurs. Thus, base.I and base[E] correspond to this.I and this[E], except this is viewed as an instance of the base class.
If base.I is just like ((B)this).I then it seems like extension methods should be allowed here.
Can anyone explain the apparent contradiction in these two statements?
Consider this situation:
public class Base
{
public void BaseMethod()
{
}
}
public class Sub : Base
{
public void SubMethod()
{
}
}
public static class Extensions
{
public static void ExtensionMethod(this Base #base) { }
}
Here are some interesting assertions about this code:
I cannot call the extension method using ExtensionMethod() from neither Base nor Sub.
I cannot call base.ExtensionMethod() from Sub.
I can call the extension method using Extensions.ExtensionMethod(this) from both Sub and Base.
I can call the extension method using this.ExtensionMethod() from both Sub and Base.
Why is this?
I don't have a conclusive answer, partly because there might not be one: as you can read in this thread, you have to add this. if you want to call it in the extension method style.
When you're trying to use an extension method from the type it is in (or - consequently - from a type that is derived from the type used in the extension method), the compiler doesn't realize this and will try to call it as a static method without any arguments.
As the answer states: they [the language designers] felt it was not an important use case scenario to support implicit extension methods (to give the beast a name) from within the type because it would encourage extension methods that really should be instance methods and it was considered plain unnecessary.
Now, it is hard to find out what is happening exactly under the covers but from some playing around we can deduce that base.X() does not help us. I can only assume that base.X performs its virtual call as X() and not this.X() from the context of the baseclass.
What do I do when I want to call the extension method of a baseclass from a subclass?
Frankly, I haven't found any truly elegant solution. Consider this scenario:
public class Base
{
protected void BaseMethod()
{
this.ExtensionMethod();
}
}
public class Sub : Base
{
public void SubMethod()
{
// What comes here?
}
}
public static class Extensions
{
public static void ExtensionMethod(this Base #base)
{
Console.WriteLine ("base");
}
public static void ExtensionMethod(this Sub sub)
{
Console.WriteLine ("sub");
}
}
There are 3 ways (leaving aside reflection) to call the ExtensionMethod(Base) overload:
Calling BaseMethod() which forms a proxy between the subclass and the extensionmethod.
You can use BaseMethod(), base.BaseMethod() and this.BaseMethod() for this since now you're just dealing with a normal instance method which in its turn will invoke the extension method. This is a fairly okay solution since you're not polluting the public API but you also have to provide a separate method to do something that should have been accessible in the context in the first place.
Using the extension method as a static method
You can also use the primitive way of writing an extension method by skipping the syntactic sugar and going straight to what it will be compiled as. Now you can pass in a parameter so the compiler doesn't get all confused. Obviously we'll pass a casted version of the current instance so we're targetting the correct overload:
Extensions.ExtensionMethod((Base) this);
Use the - what should be identical translation - of base.ExtensionMethod()
This is inspired by #Mike z's remark about the language spec which says the following:
At binding-time, base-access expressions of the form base.I and base[E] are evaluated exactly as if they were written ((B)this).I and ((B)this)[E], where B is the base class of the class or struct in which the construct occurs. Thus, base.I and base[E] correspond to this.I and this[E], except this is viewed as an instance of the base class.
The spec literally says that base.I will be invoked as ((B) this).I. However in our situation, base.ExtensionMethod(); will throw a compilation error while ((Base) this).ExtensionMethod(); will work perfectly.
It looks like something is wrong either in the documentation or in the compiler but that conclusion should be drawn by someone with deeper knowledge in the matter (paging Dr. Lippert).
Isn't this confusing?
Yes, I would say it is. It kind of feels like a black hole within the C# spec: practically everything works flawlessly but then suddenly you have to jump through some hoops because the compiler doesn't know to inject the current instance in the method call in this scenario.
In fact, intellisense is confused about this situation as well:
We have already determined that that call can never work, yet intellisense believes it might. Also notice how it adds "using PortableClassLibrary" behind the name, indicating that a using directive will be added. This is impossible because the current namespace is in fact PortableClassLibrary. But of course when you actually add that method call:
and everything doesn't work as expected.
Perhaps a conclusion?
The main conclusion is simple: it would have been nice if this niche usage of extension methods would be supported. The main argument for not implementing it was because it would encourage people to write extension methods instead of instance methods.
The obvious problem here is of course that you might not always have access to the base class which makes extension methods a must but by the current implementation it is not possible.
Or, as we've seen, not possibly with the cute syntax.
Try to cast the instance to its base class:
((BaseClass)this).ExtensionMethod()
Applied to your code:
public class Base
{
public void BaseMethod()
{
}
}
public static class BaseExtensions
{
public static void ExtensionMethod(this Base baseObj) { }
}
public class Sub : Base
{
public void SubMethod()
{
( (Base) this).ExtensionMethod();
}
}

C# prevent base class method from being hidden by new modifier in the derived class

Here's my situation. In Java I can mark a method as final in the base/super class and there is no way a derived class can mask a method of the same signature. In C# however, the new keyword allows someone inheriting my class to create a method with the same signature.
See my example below. I need to keep the orignal.MyClass public so please don't suggest that as an answer. This seems to be a lost feature moving from Java to C#:
public class orignal.MyClass{
public void MyMethod()
{
// Do something
}
}
class fake.MyClass: orignal.MyClass {
// How to prevent the following
public new void MyMethod()
{
// Do something different
}
}
EDIT: Not a duplicate.
All answers seem to suggest, it's not possible to prevent a method from being hidden/shadowed in a derived class. This became apparent while migrating some old Java code to C#. A final method in Java will not let anybody use the same method signature in any derived class. While it's great in most scenarios that C# allows a method of same signature in the derived class, it would have been great to prevent such a behavior if warranted.
// How to prevent the following
There is no way to prevent this. It's allowed by the language.
Note that, in practice, this rarely matters. If you expect your base class to be used as your class, your method will still be called. Using new only hides the method when using the DerivedClass from a a variable declared as DerivedClass.
This means that your API, if built around MyClass, will always still call MyMethod when instances are passed into your methods.
Edit in response to comments:
If you are worried about people subclassing your class in general, the only real option you do have would be to seal your class:
public sealed class MyClass
{
This will prevent people from creating a subclass entirely. If you want to allow people to derive from your class, however, there is no way to prevent them from hiding your method in their class.
You can't prevent a public method or property being masked, but why would you? It takes a deliberate action from whoever extends the base class to do this (i.e. they need to type new), so they have intended to do it, why try and stop them?
Maybe you need to switch your pattern up a bit? If the extender must use your base method then you can put something critical in it, thus forcing them to call it. Of course this is smelly if not done correctly, so if you use this approach then mark your method as virtual, then in the documentation (or method header comments) mention that the base method must be called. This way you avoid the extender having to hide/mask your method (although they still could), but they can still extend it if they want.
I'm assuming you really want to prevent someone from overriding the method - hiding a method with new cannot be prevented, but it poses no risk to the base class, so that shouldn't be an issue.
In C# methods are not overrideable by default. So you can simply prevent someone form overriding a base method by not marking it virtual or abstract. In Java methods are virtual by default, so sealing a method by using final is necessary to prevent overriding.
I think the only way is to create interface the put your method definition within it, then let the original class to implement the interface and implement the method explicitly:
interface IAnimal
{
string diary(string notes, int sleephours);
}
class Dogs:IAnimal
{
virtual public string voice()
{
string v = "Hao Hao"; return v;
}
string IAnimal.diary(string notes,int sleephours)
{
return notes + sleep.ToString() + " hours";
}
}
class Cats:Dogs
{
public override string voice()
{
string v = "Miao Miao"; return v;
}
}
You will not use diary() method via Cats instance.
For prevent of hiding base class method you can do like this:
public class Org
{
public void Do()
{
// do something
}
}
public class Fake : Org
{
public new void Do()
{
base.Do();
// do something
}
}
here the base keyword refers to Father class.
now you called method from Father class (here is Org) in child class and now this method doesnt hide anymore.

What does a function signature without implementation mean in a class definition?

Unfortunately, I can't show code, but here's the story:
I'm supposed to learn how a program we use at work works. I traced the flow of data from a user interface element into the deep internals of a function. But now, inside of a class definition I got stuck. The data I'm tracking is passed to a function. In the class there's a line with a function signature for that function, but no implementation.
How do I go about finding the implementation? All the code (except for Microsoft's) was developed in house and should reside within the project, but Go To Definition only brings me back to the signature.
We're using C# and .Net 4.0.
Here's the line:
public abstract class SomethingDoer : SomethingElse
// ...
protected abstract void DoSomething(T1 param1, T2 param2, T3 param3);
Now I'm looking for the implementing class by looking for References to SomethingDoer, but unfortunately the break point isn't hitting. Do I have the wrong class or am I missing something about abstract functions?
Without code this is really hard to answer. A function definition without implementation is usually an interface or abstract. Interfaces can have only definitions, while abstract can mix both:
public interface ISomeInterface {
void SomeMethod();
}
public abstract SomeAbstractClass {
public abstract void SomeMethod();
public void AwesomeMethod() {
// I do awesome things; look at my method body!
}
}
If you're really looking at the source code, it could be
an abstract method
a partial method
an extern method
In the first case, the implementation is in the class deriving from this class. In the second case, the implementation is in another "part" of the definition of this class, probably in another file. In the third case the implementation is inside some (native) DLL that is being imported.
Another possibility is that you're not actually looking at the source code, but only at metadata generated from an assembly reference in your C# project file.
So which of the keywords abstract, partial, or extern do you see with the method?
It's mean you have only compiled class without sorces. May be some DLLs?
Are you possibly looking at an interface?
Interfaces have the defined functions but no implementation. It's used to show that they exist and must conform to a spec.
Can't you post sample code and change the wording for us to see?

How do extension methods work under-the-hood?

A contractor where I work is using extension methods to implement CRUD on well-known internal classes that we own. I say it is better to use normal inheritance over extension methods for the following reasons.
Using extension methods obfuscates, hides & confuses the source of the CRUD methods.
I assume extension methods make heavy use of reflection (which is slower).
His logic is, "It's compiled, so it's fast." Maybe I'm wrong...but just because it is compiled doesn't mean it doesn't use reflection, nor does it mean it is faster than normal inheritance.
So my questions are:
How do extension methods work under-the-hood?
Is it better to use inheritance or extension methods on WELL-KNOWN classes that you OWN?
How do extension methods work under-the-hood?
They're just static methods; the compiler rewrites calls like myObject.MyExtensionMethod() to MyExtensionClass.MyExtensionMethod(myObject).
Is it better to use inheretance or extension methods on WELL-KNOWN classes that you OWN?
There's not single answer to this question, it all depends on the context. But usually extension methods are most useful in those cases:
you don't own the code for the extended type
the method targets an interface and will be the same for all implementations of this interface (e.g. IEnumerable<T> and Linq extension methods)
I assume extension methods make heavy use of reflection (which is slower).
No. Extension methods are resolved at compile-time, no reflection required.
That negates your performance concerns.
Is it better to use inheretance or extension methods ?
I would say neither. Use a Repository (DAL). An entity should be persistence-agnostic (so: no inheritance from a base that does CRUD) and not pretend to be involved where it's not (no extensions).
You are right that "Using extension methods obfuscates & confuses the source of the CRUD methods" but inheritance is not the solution.
Description
Extension Methods is a language feature. The compiler makes regular IL (aka MSIL or CIL) code from that. No reflection required.
More Information
MSDN - Extension Methods
Wikipedia - Common Intermediate Language
Your question and the existing answers to it are all missing the bigger picture. New developers joining an on going project should conform to the existing coding styles and standards even if they're not the new persons preferred choices.
If a change in approach represents a major functional improvement as opposed to a primarily esthetic difference it should still be discussed and approved by the entire team first.
Once that's done the change should either be mass implemented and the style guide updated to only contain the new approach, or the old approach should be marked as deprecated and modernized as the code containing it is touched. In the latter case it's best to do commit the cleanup changes separately from the addition/removal/modification of existing functionality so that why the individual modifications in the diff were made is kept clear.
In answer to the first question:
Under the hood, extensions act as Delegates, such that void MyExtension(this object obj) could be rewritten as Action MyDelegate. Where they differ, though, is in syntax when called, as Action must wrap around the object, whereas extensions can be called as if it were a member of the object itself, even though under the hood it is not (nor does it have any direct access to private or protected members of the object, for that matter).
In answer to the second question:
I usually reserve extensions for either classes I do not own or Interfaces.
For example, say you have an interface IAnimal
Public Interface IAnimal
{
void Speak();
void RunToOwnerWhenCalled();
}
And the following classes
public class Mammal
{
public virtual void AnswerWhatAmI()
{
Console.WriteLine("I'm a mammal");
}
}
public class Dog:Mammal, IAnimal
{
public void Speak()
{
Console.WriteLine("arf");
}
public void RunToOwnerWhenCalled()
{
Console.WriteLine("Comming");
}
}
public class Cat:Mammal, IAnimal
{
public void Speak()
{
Console.WriteLine("meow");
}
public void RunToOwnerWhenCalled()
{
Console.WriteLine("I don't know you");
}
}
Then you could have an extension like
Public static void CallAnimal(this IAnimal animal)
{
animal.RunToOwnerWhenCalled();
}
And a method like
Public static void Main
{
Cat cat = new Cat();
cat.CallAnimal();
}
and the result would show the cat's response "I don't know you" in Console.
Consider one more class
Public class Human:Mammal
{
Public Human():base()
{
Console.WriteLine("To be more specific, I am a human.");
}
}
This class wouldn't have the CallAnimal extension, as it does not impliment the IAnimal interface, even though it is a type of Mammal.
Under the hood, an extension method is just like a regular method, and the object it's called on is passed as the first parameter (the this parameter). There's nothing special about an extension method, it's just syntax candy.
It's good practice to avoid extension methods whenever you can. They make the code less readable and less object-oriented.
If it's a class you own, I see no reason to add an extension method to it.

Static method in abstract class to return IEnumerable<DerivedType>

Is there a way of putting a static method in an abstract class that can return the derived type?
Does a static method even know what type it is even being called from in C#?
For example, a base class could be
public abstract class MyBase
{
public static IEnumerable<TDerivedType> LoadAll()
{
//functionality here
}
}
Then if MyDerivedType inherits MyBase, I'd like to be able to call MyDerivedType.LoadAll()
Nothing too important - I'm currently using a generic static method and calling MyBase.LoadAll<MyDerivedType>(), which works fine but it doesn't look quite as 'pretty' as this would be.
Static members aren't inherited, so the static method has to be told in some way what the derived type is. Your solution is one way. Another is the following:
public abstract class MyBase<T> where T : MyBase<T> {
public static IEnumerable<T> LoadAll() { }
}
Then:
class Derived : MyBase<Derived> { }
var all = MyBase<Derived>.LoadAll();
That said, I think there is something wrong with your model. MyBase represents something in your domain (of which they are more specific derived types) AND it knows how to load all of those objects? That's two responsibilities, and that ain't cool yo.
No, there currently isn't a way to do this. I'd possibly use a factory in this case
var all = MyClassFactory.LoadAll<MyDerivedType>();
An abstract class can never be instantiated(that's the whole point) so any static methods would have to be implemented in each child class.
From an MSDN Thread
Static methods can be defined in an abstract class. However, you cannot force a derived class to implement a static method. If you think about it, such a method would be useless. Static methods are invoked using type names, not instance variables. If I call MyBaseClass.MyMethod, then MyBaseClass.MyMethod will always be invoked. How would it do you any good to force MyChildClass, which inherits from MyBaseClass, to also a implement a static MyMethod?
(Note: edited implemented to instantiated in the first sentence.)
There is nothing wrong with the way you are doing this. In fact most of MS generic extension methods are designed like this.
As for:
"Does a static method even know what type it is even being called from in C#?"
Its not a question of the static method knowing, its a question of the compiler knowing. When the code is scanned by the compiler this is when all the types are consolidated. At this point it can work out what code calls what functions and what types need to be returned. This is also the reason that a var type cannot be returned from a function.

Categories

Resources