Passing object reference to method, must it be static? - c#

When I'm trying some code to learn about passing a reference of an object to a method, I get an error when I try to remove the static in the methods head. The error message says: An object reference is required for non-static field, method or property...... But isn't there a reference in the parameter already? I have seen code that don't use static, so why does this not work? I know that static is used when method is used from classes that isn't objects. Some explanation is appreciated to understand. Thanks!
// Method
internal static string ChangeName(Box obj)
{
return obj.BoxName;
}
EDIT: I added the whole code. Is the problem that I'm calling from inside the main method that is static?
class Program
{
static void Main(string[] args)
{
Box box1, box2;
box1 = new Box("Nick","R90",1);
box2 = new Box("Hanna","B27",2);
Console.WriteLine(ChangeName(box2));
Console.Read();
}
// Methods
private static string ChangeName(Box obj)
{
return obj.BoxName;
}
}

A static method is called like this:
MyClass.Method(arg);
An instance method is called like this:
MyClass myInstance = new MyClass();
myInstance.Method(arg);
The two are not compatible.
If you want to change the method signature, you also need to change every place where the method is called.
EDIT: You are using the unqualified call. Here are the rules for using an unqualified call.
A static method can call a static method.
A static method cannot call an instance method. (This is your problem.)
An instance method can call a static method.
An instance method can call an instance method.
This method should really be implemented as an instance method in the Box class. You would then say:
Console.WriteLine(box2.ChangeName());
If you don't have access to the Box code, and then you could either write an extension method, or keep the method static as per your example.

Probably the error is where you are calling this method; if you are calling from a static method, you must call against an object instance explicitly or call a static method.

Related

delegate has to be before main ?method

Let say I have a Student class
class Program
{
delegate bool del2(Student s); //I have to put this delegate before Main?
static void Main(string[] args)
{
List<Student> listStudent = new List<Student>()
{
... //adding student instances...
};
//delegate bool del2(Student s); Q1: why compile error if I put it here?
Predicate<Student> del1 = check;
Student s = listStudent.Find(del1);
Console.WriteLine("s is" + s.Name);
}
public static bool check(Student s) //Q2:why it need to be static method?
{
return s.Name == "Michael";
}
}
I have two questions:
Why I have to put del2 before the main method? del1 is a Predicate delegate, I can put it inside the main method, del2 is also a delegate, why I can't put it inside the main method too?
Why the check method has to be static?
Short answer:
You should declare delegate and Predicate as it is done in the MSDN documents, because off course you should.
Long Answer:
You don't have to put that delegate before Main. You just can't put it inside Main. This is a type declaration. And that type(Delegate with certain signature you declared) is meant to be used for passing functions as parameters. Things you declare in main, or any other method will be valid just in that method's scope. Even if you could declare a delegate in a method, the signature would not be defined( and recognizable) at anywhere else and this would be useless.
Actually the method you assigned to a Predicate doesn't have to be static, it just have to be there when you assign it. Static functions are available without creating an instance of their class. They are independent of objects of that class. Non-static methods belong to their objects and they are specific to their objects. Their specific object code is created with object creation. So you can use a non-static function, if an available object has it. Say Student class have a non-static check method. You can do this:
Student s2= new Student();
Predicate<Student> del1 = s2.check;

How to get the object from a MethodBase class instance

I have a module (Fody.MethodTimer) that I can extend my classes with attributes. When my class'es method gets executed it, invokes a static method (in another class)
public class CommandBase
{
[Time]
public bool test()
{
return true;
}
}
public static class MethodTimeLogger
{
public static void Log(MethodBase methodBase, long milliseconds)
{
//Do some logging here
}
}
Basically, after the method is call of test is complete, the Log method gets executed. As you can see, it get a MethodBase argument and has all that is needed do decribe the method that invoked this method call.
my Question is, If it is possible to get the object that invoked the Log method Call, out of The .NET MethodBase class instance.
No. MethodBase is extracted from a type, not an instance. You will need to pass the instance in as a parameter if you want to invoke methods on it.
Even if you could, how would you know what parameter values to use when calling the method?
This is why all built-in event handlers have an object sender parameter - so you know which object triggered the event.

Oveloaded function static method error

I was going through an example which is below
class Program
{
public static void Show(String pstrMessage)
{
Console.WriteLine(pstrMessage);
}
public void Show(Object obj)
{
Console.WriteLine(obj.ToString());
}
static void Main(string[] args)
{
Program program=new Program();
program.Show("Test Message");
}
}
When I remove the static function it is working fine. Other wise it is giving me a compile time error.can't access Static method "show" in non static context.As I think object is the base class for all then it should automatically typecasted to object (implicit typcasting).
Can anyone explain why it is giving an error.
Thanks
There's no reason for Show(Object) to be a non-static member function. Declare that function static too.
Then, you'll need to use Program.Show (with the class name) instead of program.Show (with the instance name) because you're calling a static function.
When multiple method names match, the compiler runs an overload resolution procedure to decide which method is more specific. In your case, the static overload happens to be the most specific one, because it takes a string rather than object. The compiler complains that you should be calling it using Program.Show("Test Message");
If you want to use the instance function, just using program.Show((Object)"Test Message");

Explicitly call static constructor

I want to write unit test for below class.
If name is other than "MyEntity" then mgr should be blank.
Negative Unit test
Using Manager private accessor I want to change name to "Test" so that mgr should be null.
And then will verify the mgr value.
To achieve this, I want to explicitly call the static constructor
but when I call the static constructor using
Manager_Accessor.name = "Test"
typeof(Manager).TypeInitializer.Invoke(null, null);
name is always set to "MyEntity" how to set name to "Test" and invoke the static constructor.
public class Manager
{
private static string name= "MyEntity";
private static object mgr;
static Manager()
{
try
{
mgr = CreateMgr(name);
}
catch (Exception ex)
{
mgr=null;
}
}
}
As I found out today, the static constructor CAN be called directly:
from another Stackoverflow post
The other answers are excellent, but if you need to force a class
constructor to run without having a reference to the type (ie.
reflection), you can use:
Type type = ...;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
I had to add this code to my application to work around a possible bug in the .net 4.0 CLR.
For anyone finding this thread and wondering... I just did the test. It appears System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor() will only run the static constructor if it has not already been run for another reason.
For example, if your code isn't positive whether or not previous code may have accessed the class and triggered the static constructor to run, it doesn't matter. That previous access will have triggered the static constructor to run, but then RunClassConstructor() will not run it also. RunClassConstructor() only runs the static constructor if it hasn't already been run.
Accessing the class after RunClassConstructor() also does not result in the static constructor being run a second time.
This is based on testing in a Win10 UWP app.
Just add public static void Initialize() { } method to your static class and call it when you want. This is very similar to call constructor, because static constructor will be called automatically.
If you have a static member in your class (there must be, otherwise static constructor wouldn't do too much) then no need to explicitly call the static constructor.
Simply access the class where you would like to call its static constructor.
E.g.:
public void MainMethod()
{
// Here you would like to call the static constructor
// The first access to the class forces the static constructor to be called.
object temp1 = MyStaticClass.AnyField;
// or
object temp2 = MyClass.AnyStaticField;
}

Invoking non static method from static method

Can I call(access) non static method from static method ??
Like I have static method If yes, how??
public static void method() //like this is a static method
{
methodsec(); //from here I want to access non static method defined below
}
public void methodsec() // non static method
{
}
Yes, but you need a reference to do it through:
public static void StaticMethod()
{
someInstance.InstanceMethod();
}
public void InstanceMethod()
{
}
You need to think about which instance you want to call the method on. Instance methods typically use the state of the instance, so the method is likely to do different things depending on which instance it's called on.
No you can't call it exactly like that. You either need an instance of the class to call the non-static method, or it also needs to be static.
An alternative approach would be to use a singleton pattern - so you only have one instance of the class available throughout your code, and don't need to use static methods. That way, all methods in the class can call each other. It's hard to tell whether this would actually suit your needs, without further info but could be the way to go

Categories