I got a C# project which needs to be rewritten to java. Unfortunately the original programmer cannot be reached and I have some troubles with some of the C# specific things in the project.
Lets say we have a class in C# like:
public static class MySampleClass : Object
{
...
public static IEnumerable<MyObject> MyFunc(this MyObject t) {
//a lot of code
}
...
}
I dont understand the this before the parameter in this function. What does it reference to? I mean we're in a static class and a static function, so whats "this"? Is it just a reference to t then?
And of course my question would be that this function header is substitute for this in Java:
public static Iterable<MyObject> MyFunc(MyObject t)
Or do I need to do anything else?
Thank you for your help
In this case this refers to any instance of MyObject. It's called extension method:
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type. Extension methods are a special kind of
static method, but they are called as if they were instance methods on
the extended type.
It defines a method which can be used on instances of MyObject class. There is no such thing in Java, so you have to add this method to MyObject class.
Extension methods, like walkhard pointed out in his answer, can be declared anywhere and can simply be called like if they had been declared within the class.
This does not exist in Java. You will have to add MyFunc to the declaration of that Java class.
Using this in that way makes the method an extension method. Java does not have an equivalent. In C#, it is syntactic sugar that lets you do the same thing as this:
MySampleClass.MyFunc(myObject);
With this code:
myObject.MyFunc();
(These compile to the same thing, as long as MySampleClass's namespace is imported and MyObject doesn't declare its own MyFunc() method.)
Since this doesn't exist in Java, you should simply replace myObject.MyFunc() with MySampleClass.MyFunc(myObject).
It's an extension method it permit to any object of type MyObject to expose the method MyFunc and use it as a normal instance method (but in reality it's not) it's a normal class method
MyObject o=new MyObject();
//whitout extension method
MyObject.MyFunc(o);
//with extension
o.MyFunc();
It's a syntactic sugar that doesn't exist in java so you have to modify class MyObject and adding instance method MyFunc if you don't want to change all the calls to MyFunc or write a static function and modify every call to MyObject.MyFunc(o);
Related
Converting some code from Swift to C#. There's a need in a base class's static method implementation to know which concrete type that method was called against.
In Swift, when in an instance method, you use self (lowercase) to get that instance. This is equivalent to using this in C#. To get the instance type, you use Self (uppercase) which is the equivalent of C#'s this.GetType().
However, Swift also lets you use lower-cased self from within a static method to get the type the static was called against (as opposed to the type where it was defined.) I'm trying to find if C# has something similar. We're using C# 9 if it matters.
Here's a simple example showing what we're after. Note, this will not compile. It's example only since self isn't known to C#.
public class BaseClass {
public static void DoSomethingStatic(){
// Looking for the equivalent of Swift's 'self' in a static method
// which returns the concrete type, including when called from a derived class
Debug.WriteLine($"Static method called on the type {self.FullName}.");
}
public void DoSomethingInstance(){
// Swift's 'Self' in an instance method is equivalent to C#'s `this.GetType()`
Debug.WriteLine($"Instance method called on the type {this.GetType().FullName}.");
}
}
public class MyClass : BaseClass {}
Now this is easily possible with instance methods thanks to using this.GetType():
var myClass = new MyClass();
myClass.DoSomethingInstance();
Output:
Instance method called on the type MyClass.
But we're hoping to achieve the same thing from a static exposed via the base class, like this...
MyClass.DoSomethingStatic();
Output:
Static method called on the type MyClass.
So is this possible in C#9?
This question already has answers here:
Why are extension methods only allowed in non-nested, non-generic static class?
(3 answers)
Closed 9 years ago.
Just now i read about Extension methods.I created static method inside static class its working fine.
static class ExtensionMethods
{
public static string splitFirstName(this string strName)
{
return strName.Split(" ".ToCharArray())[0];
}
}
But If i create static method inside Nonstatic class its not working.
class NonStaticCls
{
public static string splitFirstName(this string strName)
{
return strName.Split(" ".ToCharArray())[0];
}
}
Please tell why its not working in nonstatic class.
Please tell why its not working in nonstatic class.
Because that's just how extension methods are specified. They must be declared in a non-nested, non-generic class.
From section 10.6.9 of the C# 5 specification:
When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.
Why do you want to declare it in a non-static class? What are you trying to achieve which can't be achieved equally well using a static class? (I can just about imagine some possibilities, but they're not things I've ever wanted to do in extension methods myself...)
It's a requirement that the class be static. This is reasonable. If it wasn't a static class, you'd be able (potentially) to create instances of that class. But then it has extension methods in it, possibly for other, completely unrelated classes. That could be very confusing.
That's by design behavior. Extension method can only be declared in static class.
How to: Implement and Call a Custom Extension Method (C# Programming Guide)
To define and call the extension method
Define a static class to contain the extension method.
Looks like it's by design.
From MSDN;
The following list provides the main features of a static class:
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
Check out this answer from Eric Lippert
Why are extension methods only allowed in non-nested, non-generic static class?
Also from AskJonSkeet
It's dictated in the language specification, section 10.6.9 of the C#
4 spec:
When the first parameter of a method includes the this modifier, that
method is said to be an extension method. Extension methods can only
be declared in non-generic, non-nested static classes. The first
parameter of an extension method can have no modifiers other than
this, and the parameter type cannot be a pointer type.
According to C# spec. you can read more here Extension Methods
Extension methods can only be declared in non-generic, non-nested
static classes.
AS other pointed you, you need to include the static.
basically you will create a bunch of extension method as Utility Project or Helper Class
Creating static class you need not to instantiated, and invoke the method directly. for Eg. Math.Pow()
as per your question, Extension method work only when it's in Static class. and use of proper namespace.
I saw things like this:
public static void FunctionSample(**this** Class1 x, int r, double f){
what does "this" do?
Ths means an extension method to Class1, although in current form its incorrect since the method needs to be static as well and inside a static class.
Extension Methods (C# Programming Guide)
Extension methods are defined as static methods but are called by
using instance method syntax. Their first parameter specifies which
type the method operates on, and the parameter is preceded by the
this modifier.
It means that the method you're creating is an extension method. This means (in your case) that the method will act as if it were a member method of Class1. So you could just use this:
Class1 exmpl = new Class1();
exmpl.FunctionSample(0, 0.0);
However, it won't work in your case, since extension methods need to be static, and exist in a static class.
If you want the extension methods to work like the example given above, you will need a using directive to the namespace the static class containing the extension methods is in.
In fact, this is how linq works as well. If you add using System.Linq to your code file, the only thing you're doing is importing a load of extension methods.
I know (or so I hear) that writing extension methods for a single stand alone .net class (not an implementation of IEnumerable) is potential code smell. However, for the sake of making the life easier I need to attach a method to the ConfigurationManager class in asp.net. It's a static object so this won't work:
public static List<string> GetSupportedDomains(this ConfigurationManager manager)
{
//the manager needs to be static.
}
So the question is - is it possible to write an extension method for a static class in .net?
No, it isn't possible.
They are defined as static objects that appear to be instance methods.
From MSDN:
Extension methods are defined as static methods but are called by using instance method syntax.
No you can not. Extension methods require an instance of a given type, which you cannot get from a static class.
How to understand the following code? What does "this" mean in the generic function prototype? Thanks!
public static class MyExtensions
{
public static MyStream<T> MySingle<T>(this T source)
{
return new MyStream<T>(source);
}
}
this in this context means it is an extension method so you can either use it the "normal" way:
MyExtensions.MySingle(someSource)
or this (sometimes nicer) way:
someSource.MySingle()
This is only possible when the method is static and is in a static class. Also, it have nothing to do with the generic aspect of the method - you can make extension methods without generics aspects and you still have the this in front of the parameter.
Extension methods, as the name suggest, is used for extending already existing classes with methods if you don't have access to the source or if you want it to be used over a broad set of classes. It is important to note, that you don't get access to private and protected methods etc., like when you derive from the class, when you make a extension method on a type.
Also, for a in-depth explanation:
Extension Methods (C# Programming Guide)
That it is an extension method, that becomes a valid method of all objects of type T.
It has nothing to do with generics.
MySingle<T> is defined as an extension method (MSDN).
This means that in usage you can call it like this:
MyStream<string> stringStream = "a string".MySingle();
This is identical to calling it in the "standard" way:
MyExtensions.MySingle("a string");
When you call it the first way (as an extension method), the item on which it is called is passed as the first parameter. The type of the first parameter therefore defines the type on which the extension method can be called, but since you have an open generic type, it can be called on any object.
To define an extension method, the containing class and the method itself must be declared static.
Extension methods were added in C# 3.0 and VB 9.0.
This is an extension method, this is the instance that the method is applied to.
Yes it is an extention method but as far as i understand he is also asking what does it mean using a T (generic type definition) with "this" keyword in the method signature.
It means that the extention method will be valid method for all objects of every class and struct types in your project.
This indicates it is an extension method. The type being extended is 'T'.
All instances of 'T' will have method MySingle .