This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 6 years ago.
Is it possible to add an additional static method to .Net string class so I could write:
var header = string.FormatHeader(str1,str2,str3,formatOption);
TLDR:
No.
Bit more:
Extension methods must recieve an instance to work on:
void static Foo(this string s)
{
// Do something
}
There is no syntax for just off the string.
No it's not possible, extension methods are just syntactic sugar. It will be converted by the compiler to something like StringExtensions.FormatHeader(..);. The best you can do here is to create something like a helper class to handle this for you.
public class StringHelper
{
public static string FormatHeader(string str1, string str2, string str3, FormatOption formatOption)
{
throw new NotImplementedException();
}
}
No, you can't add new static methods to the string class. You'd be better off writing your own StringUtils class or HeaderUtils class or something if there's no logical class for it to be a member of.
Related
This question already has answers here:
What is the use of making constructor private in a class?
(23 answers)
Why do we need a private constructor?
(10 answers)
What is the need of private constructor in C#?
(12 answers)
Closed 4 years ago.
use of private constructor :
it cant able to create instance,
it cant be inherit,
it contain only static data members
without private constructor also i can able to access class with its static declaration and static data member when assign value like the below example
class Test
{
public static int x = 12;
public static int method()
{
return 13;
}
}
class Program
{
int resut1 = Test.x;
int resut2 = Test.method();
static void Main(string[] args)
{
}
}
so i have doubts as below
why should go to private constructor
what is the use of private constructor block
is we cant do anything inside of private constructor block
when it execute please explain clearly
thanks in advance
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static. For more information see Static Classes and Static Class Members.
Follow this https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors
A private constructor prevents the generic default constructor from being used.
The generic default constructor allows a class to be instantiated; while, a private constructor.
According to this microsoft doc, they are generally used to prevent people from instantiating classes that only have static members/functions.
This question already has answers here:
Method can be made static, but should it?
(14 answers)
Closed 8 years ago.
Consider the following class:
public class Extractor
{
public IService service;
public Extractor(IService service)
{
this.service = service;
}
public void DoSth()
{
var sampleMethodInfo = this.service.GetMethodInfo();
var version = ExtractAvailableMethodVersion(sampleMethodInfo);
// other stuff
}
private int ExtractAvailableMethodVersion(MethodInfo methodInfo)
{
var regex = new Regex(MIGRATION_METHD_NAME_EXTRACT_VERSION);
var matcher = regex.Match(methodInfo.Name);
return Convert.ToInt32(matcher.Groups[1].Value);
}
}
Resharper hints to make ExtractAvailableMethodVersion static. So my question is - should I make static method everywhere it's possible (like in the example ablove)? Is any performance difference when calling static / non-static method in such a case? Or is it only "code-style rule" to make static method when not using instance members?
You don't make methods static just when possible, you do it when it makes sense, ie. what method does is not related to specific instance, but to a class in general.
Evaluate whether this is the case here, but you are not using current instance anywhere in the method, so above might be the case.
This question already has answers here:
Java equivalent to C# extension methods
(14 answers)
Closed 9 years ago.
I am posting a C# example of extension usage, to make my question more clear. I have a simple class called Parameter with two properties: a key and a value. And I am extending the List of Parameters to be able to check if a certain key is contained in the List:
Parameter Class:
public class Parameter
{
private String key { get; set; }
private String value { get; set; }
}
Parameter Extension Class:
public static class ParameterListExtension
{
public static bool contain(this List<Parameter> parameters, String key)
{
foreach (Parameter parameter in parameters) {
if (parameter.key.Equals(key)) { return true; } }
return false;
}
}
Usage of Extension:
List<Parameter> parameters = getParameters();
if (parameters.contain("myParameter")) { ... }
Can this be done in Java?
There is an extension to Java, called Xtend, that adds support for extension methods (among other features). Some of the features of Xtend are supposed to come with Java 8. In my experiance, Xtend is sometimes nice, especially when writing tests, but the tool support in Ecplise is far worse than for pure Java. As far as I know there are no other IDEs supporting Xtend.
In Java 7 and earlier, there is no way to do this as described. The solution is to use a "helper" class as described in the other answers.
In Java 8, you can "sort of" do this using default methods. Consider the following:
public interface Parameter {
// getters and setters
}
public class ParameterImpl implements Parameter {
// Implements the getters and setters and the state variables.
}
Now suppose that we modify the Parameter as follows:
public interface Parameter {
// getters and setters as before
public default boolean contain(this List<Parameter> parameters, String key) {
// (Do not copy this! There are better ways to code this in Java 8 ...
// ... but that is beside the point.)
for (Parameter parameter : parameters) {
if (parameter.getKey().equals(key)) {
return true;
}
}
return false;
}
}
We can make this change to the interface (in the forward direction) without modifying the classes that implement the interface, and without breaking binary compatibility.
Of course, this only works if we had the foresight to create a separate interface and class. (But if we didn't do that, I would have thought is was no a "big deal" to modify the Parameter class to add the extension method.)
There is no such mechanism in Java to extend the behavior of a defined class out of your control. Alternatively, helper class and interface can be defined and used, though they don't 100% serve the purpose especially when visibility is a concern.
public class ParameterListExtension
{
public static boolean contain(List<Parameter> parameters, String key)
{
for(Parameter parameter:parameters)
if(parameter.key.equals(key)) return true;
return false;
}
}
…
import static ParameterListExtension.contain;
…
List<Parameter> parameters = getParameters();
if(contain(parameters, "myParameter")) { ... }
I don’t see the advantage of obfuscating where the method came from and pretending it was an instance method of the list.
I want to, for example, add a method to integer (i.e., Int32), which will make me able to do the following:
int myInt = 32;
myInt.HelloWorld();
One can say, instead of insisting doing the above, you can write a method which takes an integer, HelloWorld(integer), like the following, more easily:
int myInt = 32;
HelloWorld(myInt);
However, I'm just curious whether it's possible or not. If true, is that a good programming practice to add some other functionality to well known classes?
PS: I tried to make another class which inherits from Int32, but cannot derive from sealed type 'int'.
You can add an extension method for int32.
public static class Int32Extensions
{
public static void HelloWorld(this int value)
{
// do something
}
}
Just remember to using the namespace the class is in.
I think you mention extension method programming guide of extension method
You're after Extension Methods.
There is nothing wrong with them OOP speaking because you don't have access to private variables nor alter the behaviour of the object in any way.
Its only syntactic sugar on what you've described exactly.
Q: Is that a good programming practice to add some other functionality to well known classes?
This type of discussion really belongs on 'Programmers'.
Please take a look at this discussion on Programmers, that has a lot of philosophical points on using extension methods:
https://softwareengineering.stackexchange.com/questions/77427/why-arent-extension-methods-being-used-more-extensively-in-net-bcl
Also:
https://softwareengineering.stackexchange.com/questions/41740/when-to-use-abstract-classes-instead-of-interfaces-and-extension-methods-in-c?lq=1
Use Extensions methods
static class Program
{
static void Main(string[] args)
{
2.HelloWorld();
}
public static void HelloWorld(this int value)
{
Console.WriteLine(value);
}
}
You may use extension method
like this:
public static class IntExtensions
{
public static string HelloWorld(this int i)
{
return "Hello world";
}
}
How is it possible to make prototype methods in C#.Net?
In JavaScript, I can do the following to create a trim method for the string object:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
How can I go about doing this in C#.Net?
You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.
You can, however, in C# 3.0, use extension methods, which look like new methods, but are compile-time magic.
To do this for your code:
public static class StringExtensions
{
public static String trim(this String s)
{
return s.Trim();
}
}
To use it:
String s = " Test ";
s = s.trim();
This looks like a new method, but will compile the exact same way as this code:
String s = " Test ";
s = StringExtensions.trim(s);
What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?
It sounds like you're talking about C#'s Extension Methods. You add functionality to existing classes by inserting the "this" keyword before the first parameter. The method has to be a static method in a static class. Strings in .NET already have a "Trim" method, so I'll use another example.
public static class MyStringEtensions
{
public static bool ContainsMabster(this string s)
{
return s.Contains("Mabster");
}
}
So now every string has a tremendously useful ContainsMabster method, which I can use like this:
if ("Why hello there, Mabster!".ContainsMabster()) { /* ... */ }
Note that you can also add extension methods to interfaces (eg IList), which means that any class implementing that interface will also pick up that new method.
Any extra parameters you declare in the extension method (after the first "this" parameter) are treated as normal parameters.
You need to create an extension method, which requires .NET 3.5. The method needs to be static, in a static class. The first parameter of the method needs to be prefixed with "this" in the signature.
public static string MyMethod(this string input)
{
// do things
}
You can then call it like
"asdfas".MyMethod();
Using the 3.5 compiler you can use an Extension Method:
public static void Trim(this string s)
{
// implementation
}
You can use this on a CLR 2.0 targeted project (3.5 compiler) by including this hack:
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute
{
}
}