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.
Related
This question already has answers here:
Why could C# overload two methods with the same params as long as one of them has default param?
(2 answers)
Optional Parameter vs Empty Parameter Methods and Constructor with Overloading
(1 answer)
Closed last year.
Background
I'm working with unity which seems to be serialising classes using some parameterless constructors it creates.
The following code did not properly initialise values:
public WarmthProvider(float initialWarmth = 1)
{
this.warmth = initialWarmth;
}
My solution looks like this:
public WarmthProvider(float initialWarmth)
{
this.warmth = initialWarmth;
}
public WarmthProvider() : this(1)
{
}
(no, this is not in a monobehaviour class)
Question
When implementing this, I noticed the following was perfectly legal and compiled:
public WarmthProvider(float initialWarmth = 1)
{
this.warmth = initialWarmth;
}
public WarmthProvider() : this(1)
{
}
Why is this possibly allowed? Surely this is ambiguous as to which constructor to call? Do these not now have the same signature? Is there any reason allowing this syntax is better than it being illegal?
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:
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.
This question already has answers here:
An object reference is required to access non-static member
(2 answers)
Closed 4 years ago.
I apologise, I know this question has been asked a thousand times before by C# beginners (of which I am one), but all the answers I can find say I need to either instantiate the class, or make it static. My class is instantiated, and I am trying to access the instance. Can anyone take a look at my code and work out what is going wrong?
public class RocketSimMain {
public RocketShip test = new RocketShip ();
public static void Main() {
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested()) {
test.Move(); <- Object instance error here.
}
}
}
As you can see, I'm instantiating the class and accessing the instance. The only thing that works is instantiating the class inside the Main method, but then I'm not able to access it in other classes.
You have to make test static in order to use it from a static method (Main).
This problem arises because you are trying to call a non-static class from a static method.
To solve it you must either make them both non-static:
public RocketShip test = new RocketShip ();
public void Main()
{
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested())
{
test.Move(); <- Object instance error here.
}
or instantiate it locally within the method:
public static void Main()
{
RocketShip test = new RocketShip ();
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested())
{
test.Move(); <- Object instance error here.
}
}
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.