Static modifier requirement in class/page - c#

EDIT : Sorry. It seems I got a little confused. I was attempting to call a non-static method within a static method, and it wasn't working. They were in the same class. That led me to (incorrectly) assume that I cannot call a non-static without instantiation, even though they belong to the same class.
Since I already created the question, allow me to change the question a little. Why can I not call a non-static method within a static one? Here's my code so that you can tell me if I'm just screwing myself over with something silly:
public class DataAccessObjectClass
{
public static IList<Records> GetAllRecords(Dictionary<string,string> searchDic)
{
string query = BuildSearchQuery(searchDic); //error: object ref. required
}
public string BuildSearchQuery(Dictionary<string,string> searchDic)
{
string query = "";
//build the query
return string;
}
}

Is it something in the System.Web.UI.Page class?
No, It is because you're already inside the instance method. There is an implicit instance this which already exist in the context, this instance will be used to call that method.
There is nothing special with Page class, in any class you can do the same, You can call whatever instance method from another instance method without an instance(although you're technically using this as implicit reference).

You don't need to instantiate the class because it's already been instantiated for you.
Consider the class
public class C
{
public void f() { g(); }
public void g() { }
}
Now, you cannot simply call C.g();, you need an instance to call it on. new C().g(); would work, but so would
var c = new C();
c.g();
The call from f to g already has an instance to call g on, which is this. There, g(); simply means this.g();. c.f(); would end up calling c.g() from within f.
For your edited question, consider this class:
public class D
{
public static void f() { g(); } // error
public void g() { }
}
Now, because D.f is static, you could call it as simply D.f();. In that case, there isn't any instance of D at all yet, so you have no instance to call g on. (Or, if you do create instances of D first, the system wouldn't know which of those instances to call g on.)

Actually, Page_Load is beeing called when the page is rendered, so, there is an instantiate of the class DefaultPage, and this object is the one that is calling to Page_Load and to GetObjects.

Related

How am i able to pass private object to another class by reference?

I just noticed that i am able to pass private object to another class by a reference
I would guess this should not be possible but it works fine
Here an example
private static StreamWriter swYandexErrors; // in classA
csLogger.logAnyError(ref swYandexErrors, $"msg", E); // in classA
// in class csLogger
public static void logAnyError(ref StreamWriter swError,
string srError, Exception E = null)
{
lock (swError)
{
swError.WriteLine("");
swError.Flush();
}
}
private means just private for that variable, not for the actual instance which is referenced by that variable. So the reference swYandexErrors which is private in your class is of course not visible to the other one. However as you´re passing the instance by reference you can of course access the instance within your first class.
To be more clear the following does not work in class csLogger and causes a compiler-error as you can´t access swYandexErrors within csLogger:
public static void DoSomething()
{
ClassA.swYandexErrors.Read();
}
As an aside: you don´t even need the ref-keyword in your method, as you don´t re-assign the passed StreamWriter. All you´re doing is to call members on the passed instance.

What's the meaning of making a method static? -For dummies [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have a method that takes a string argument (a file path), and i wanna make it acessible to all forms.
I know that when i use
public static methodname(string path) { //code }
it will work on all forms as long as i call it, and when i dont have static there i have to instantiate it.. the thing is.. why this difference? What does it really means to instantiate? I've read a few topics about it, but i couldn't quite understand how, can you take the time to explain it to a amateur beginner?
This tells the compiler that he method is entirely self-contained, and does not rely on or utilize any object state, or instance-based properties or fields of the class it is defined in. As a consequence, you do not need to instantiate an instance of the type (class or struct) in order to use this method. It becomes like a global function or subroutine which you can call simply by name, (you must use the class/struct name and method name) without any preparation.
to call non-static method MyMethod() on class foo
var f = new foo();
f.MyMethod();
to call static method MyMethod() on class foo
foo.MyMethod();
You can define static methods in a non-static class, (if the method does not rely on any object state doesn't mean the object does not have any state...). but you cannot put non-static methods in a static class (if the method requires access to object state, then it obviously can't be in a class that has no state).
Now you can write a method that does not require object state, and neglect to declare it as static. Then it would require the same usage syntax like a non-static method even though it is functionally static. That is an error the compiler will accept (although many tools like Resharper will warn you about this).
You use non-static classes or object oriented classes, if you want to maintain a state.
When you use static classes, there isn't any state.
For example:
class HelloWorld
{
public string Name {get;set;}
public void SayHello()
{
Console.WriteLine(Name + " hello!");
}
public void SayHi()
{
Console.WriteLine(Name + " hi!");
}
}
You would use the above like this:
HellowWorld obj = new HelloWorld();
obj.Name = "John";
obj.SayHi();
obj.SayHello();
If that was a static class:
static class HelloWorld
{
public static void SayHello(string Name)
{
Console.WriteLine(Name + " hello!");
}
public static void SayHi(string Name)
{
Console.WriteLine(Name + " hi!");
}
}
You would call the above like this:
HelloWorld.SayHello("John");
HelloWorld.SayHi("John");
As you can see, you are repeating yourself.
So it all depends on how you want the class to behave. If you want do and forget, then static class is your friend. If you don't want it to forget something, then use Objects
This is classic programming. Static methods are used when all the data you need is from the parameter. Also static methods are called upon a class. When you make a method static then it uses instance variables to do something. Instantiontain allows a user to initialize all fields in that class then the user can call a method upon that object that behind the scenes uses instance variables to do something.
As you said, a non-static method means that it belows to an object (so you have to instantiate one in order to use the method. On the other hand, a static method below to the class, so when you call it, it has nothing to do with an object.
For example:
class C{
static int f(int i){return i+1;}
}
C.f(2); // returns 3
You only can do it if the method is static, it is, it belongs to a class, not an object. If f() were not be static, you have to instantiate one object to use it:
class C{
int f(int i){return i+1;}
}
C.f(2); // invalid!
C c = new c(); c.f(2); // returns 3
On the other hand, this code is invalid:
class C{
int a;
static int f(){return a;}
}
C.f(); // Invalid: each instance of C has it own attribute a.

Why Static Methods are allowed only to call static methods not non static methods [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can I only access static members from a static function?
While I was trying to call a normal method from inside a static method I got the error:
An object reference is required for the non-static field, method, or property
So this means I need to create the object of the Class and then call the nonstatic method. If I want to call the method directly then I have to declare that method as Static.
But , in this scenario , the calling method and called method belong to same class. So Why do I need to create an object while calling from a Static Method , while I can call a non-static method from non static method.
Ex:
class Program
{
//public void outTestMethod(int x,out int y)
//{
// y = x;
//}
static void Main(string[] args)
{
int a = 10;
int b = 100;
outTestMethod(a,out b);
}
private void outTestMethod(int x, out int y)
{
y = x;
}
}
Error:An object reference is required for the non-static field, method, or property
Static methods can call instance methods - but you need to have an instance on which to call them. It doesn't matter where that instance comes from particularly, so for example:
int a = 10;
int b = 100;
Program program = new Program();
program.outTestMethod(a,out b);
Instance methods are associated with a particular instance of the type, whereas static methods are associated with the overall type instead - and the same is true for other kinds of members. So to call an instance method, you need to know which instance you're interested in. For example, it would be meaningless to have:
string name = Person.Name;
because you need to know which person you're talking about:
Person person = FetchPersonFromSomewhere();
string name = person.Name;
... that makes much more sense.
Typically instance methods use or modify the state of the instance.
Consider it this way.
A static method is the button outside a bank of elevators. Anyone can see it and push it, and make something happen (i.e. one of the elevators will arrive at that floor).
The non-static methods are the buttons inside a specific elevator. They manipulate THAT elevator (and none of the others).
A non-static method is also called an instance method. This means there (usually) is a chunk of data, specific to the instance (object) that the method operates on.
You can't call a non static or instance method from a static method because it wouldn't know which instance or object to operate on.
Because there is no instance to call the method from. YOu should create possibly another class and test on that:
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 100;
Test testclass = new Test();
testclass.outTestMethod(a,out b);
}
}
class Test
{
public void outTestMethod(int x, out int y)
{
y = x;
}
}
do you understand the difference between instance method and static method?
an instance method has access to the this object even if it's not passed in as parameter, in fact it's like if it was an invisible parameter of the same type of the class passed for you by the framework.
a static method does not have that this object and cannot call instance methods because it does not have anything to pass for that this in the invisible way...
sounds like a joke but this is the way I see it :)

Can I use some other class's function as a delegate?

Say I have 2 classes, class A and class B. Class A creates an instance of Class B. Class A has a function that I would like to pass into a method from Class B.
class A {
void Main(string[] args) {
B classB=new B();
DelegateCaller(new delFunction(classB.TheFunction()); // <-- Won't compile (method name expected)
DelegateCaller(new delFunction(B.TheFunction()); // <-- Won't compile (object reference is req'd)
}
public delegate string delFunction();
public DelegateCaller(delFunction func) {
System.Console.WriteLine(func());
}
}
class B {
public string TheFunction() {
return "I'm Printing!!!";
}
}
I'm not sure if it a syntax issue or it's just something I can't do. Maybe I need to define the delegate in B, but reference it in A? What about B's this pointer?
It's just a syntax issue; get rid of the parentheses after classB.TheFunction - they indicate that you wish to invoke the method.
DelegateCaller(new delFunction(classB.TheFunction));
Do note that there is an implicit conversion available from a method-group, so you can just do:
DelegateCaller(classB.TheFunction);
Also note that creating your own delegate-type in this case is unnecessary; you could just use the in-built Func<string> type.
EDIT: As Darin Dimitrov points out, there is also the unrelated issue of calling an instance method as though it were a static method.
Try like this:
class A
{
static void Main()
{
B classB = new B();
DelegateCaller(classB.TheFunction);
}
public delegate string delFunction();
public static void DelegateCaller(delFunction func)
{
Console.WriteLine(func());
}
}
class B
{
public string TheFunction()
{
return "I'm Printing!!!";
}
}
Let me elaborate about the different changes I've made to your initial code:
TheFunction in class B needs to be public so that you can access it from class A
The DelegateCaller method in class A should be static and not necessarily return a value (declare it as void) if you want to call it from the static Main method.
The definition of the delFunction delegate should return a string.
Take the parenthesis off the end of TheFunction. You want the method, not the result of a call to the method.
If you want to capture an instance method for usage in a general purpose fashion you should use Delegate.CreateDelegate(Type,MethodInfo). This is nice as it allows you to create an "open delegate" meaning it isn't bound to an instance and can take any instance that is a ClassB. It makes reflection quite fast if you know the type information, as this method will perform much faster than the equivalent statement using MethodInfo.Invoke.
DelegateCaller(new delFunction(B.TheFunction());
Should be
DelegateCaller(new delFunction(B.TheFunction);
To use classB.TheFunction you would need to make TheFunction static. You pass in the function with no parens.

Static property references non-static method

How can a static property reference a nonstatic method?
Example:
public static int UserID
{
get
{
return GetUserID();
}
}
private int GetUserID()
{
return 1;
}
When I try to compile this, I get the error: "An object reference is required for he non-static field, method or property "GetUserID()"
This doesn't work.
When you define a static property (or static method), you're defining a property that works on the class type, not on an instance of the class.
Instance properties and methods, on the other hand, work upon a specific, constructed, instance of a class. In order to use them, you need to have a reference to that specific instance. (The other way around, however, is fine.)
As an example, think of Fruit, and an "Apple" class. Say the apple class has an instance property that is how ripe the Apple is at this point in time.
You wouldn't as "Apple" to describe how ripe it is, but rather a specific "Apple" (instance). On the other hand, you could have an instance of an apple, and ask it whether it contains seeds (which might be defined on the Apple class itself (static)).
You'll just have to create a new instance:
public static int UserID
{
get
{
return new MyClass().GetUserID()
}
}
Well, you don't have to create a new instance every time UserId is called -- you can have a static field containing an instance of MyClass instead (which of course would be an approach toward implementing the Singleton pattern).
Although you can read that your static property is calling a method that could be made static, the other method isn't static. Thus, you must call the method on an instance.
You need somehow to get an instance. Without an instance, it's impossible to call an instance method.
For your case, are you sure that you need GetUserID() to be an instance method? It returns anyway the same value. Or, if your code is just dummy, and you require more logic in GetUserID(), maybe you can tell us what you intend to do?
An easy way to think about it is the following: a non-static method (or property, because properties are just wrapped-up methods) receives, as a first hidden parameter, a reference to the instance on which they operate (the "this" instance within the called method). A static method has no such instance, hence nothing to give as first hidden parameter to the non-static method.
Simply it can't.
If you need to call a static method to invoke an instance method, probably you want a Singleton
Try look at:
http://en.wikipedia.org/wiki/Singleton_pattern
Example:
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
private Singleton() { }
public static Singleton Instance
{
get
{
return _instance;
}
}
public static int UserID
{
get
{
return _instance.GetUserID();
}
}
private int GetUserID()
{
return 1;
}
}

Categories

Resources