Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Generally static variables declared for which field is common or share to the all instance of the class but i want when to use static methods c#


please help me.


thank u.

What I have tried:

Generally static variables declared for which field is common or share to the all instance of the class but i want when to use static methods c#
Posted
Updated 3-Oct-17 10:02am
Comments
PIEBALDconsult 3-Oct-17 20:08pm    
When you realize that OOP is unsuited to the situation.

You use static methods when the method does not need to access any non-static class elements such as properties, events, or methods in order to do it's job.

Think of it this way: how many wheels does a car have? What colour is a car?
The first is a static question, because all cars have 4 wheels (if they had two they would be motorcycles, and three would make them tricycles). You don't need to establish which car you are talking about, because the question is generic to all cars.
The second is non-static: you have to indicate which car you are talking about. "My Car" is black; "Your Car" is green; "This car" is red; "That car" is blue - you cannot answer the question unless you know which car you are talking about.

Classes are the same: static methods (and properties, fields, events) when you don't need information about a specific instance, non-static when you do:
C#
public class Car
   {
   private Color colour;
   public static int CountWheels() { return 4; }
   public Color GetColour() { return colour; }
   }
 
Share this answer
 
v2
Comments
Richard Deeming 3-Oct-17 15:03pm    
"all cars have 4 wheels"

Ahem![^]

And I say again, ahem![^]

:D
OriginalGriff 3-Oct-17 16:29pm    
:DOne of them is a tricycle - if you'd ever driven one (and I don't recommend it) you'd know they are classed as three-wheeled motocycles. Hideous, vile, heaps of Visual Basic...
The other is called a car but it's a bit dodgy as well.

All the best rules have exceptions though:
https://media.wired.com/photos/59322d3044db296121d69883/master/pass/Tyrrell-P34-ft.jpg
http://www.algysautosblog.com/wp-content/uploads/2013/11/FAB-1.jpg

(and they were both rubbish as well!)
Static methods imho should only be used to return one or more of the same type. For example:

/psudo code
Public static MyClass GetById(int id){...}
Public static List<myclass> SelectAll(){...}

These methods are stateless and if you have many objects it's a good way to organise the returns. This is a pretty good way to handle context models but no use when dealing with dependency injection

Just to reiterate: imho!
 
Share this answer
 
What about The Documentation[^]?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900