Why we use Static Members on C#? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can someone explain what is main difference between Instance and Static Members with real examples?

Static Members are run without using the implied "this" parameter which is the instance reference to the object that Instance Method was called from.
var number = Int32.TryParse("1234"); // Static member of Int32.
//Is not called using an object, it doesnt not need the 'this'
//because it doesn't change the data of the class.
string stringy = "asdfasdf";
char [] characters = stringy.ToCharArray();
//requires the strings data so it needs the instance stringy.
If the classes data is needed then you need an instance. If not you can make the method static so that it can be called at any time without an object.
Edit: I Initially read that as static methods. Static Data Members are completely different. When your program runs there is exactly one data object of that type allocated and is accessible via the class name not an instance of the class.
public class Classy
{
public static int number= 4;
public static void func() { }
// Other non-static fields and properties...
}
//mainline..
//
int n = Classy.number;
Classy.func(); // etc..

You don't create instances for static classes. You just call them using their type name.
For example.
public static StaticClass {
public static void StaticMethod(){}
}
To call the static method, you will just type this, StaticClass.StaticMethod().
When you create an object of a class, it is known as creating an instance of that class. You can only create instance of concrete classes).
For example
public class ConcreteClass {
public void RandomMethod(){}
}
To call RandomMethod, you will have to create an instance of the ConcreteClass by creating an object.
ConcreteClass abc = new ConcreteClass();
abc.RandomMethod();
Also note that, in a static class, all it's members will have to be static and this makes sense because, since you will not be instantiating the class, you should be able to call it's members directly. This is why in my static class example above, the method too is also static.
I hope this helps.

Related

Does a static method in a non-static class make it a static class c# [duplicate]

This question already has answers here:
What is a "static" class?
(11 answers)
Closed 2 years ago.
Possibly a stupid question but I need to ask it anyway for my own context. I have a non-static class that has a static method and a non-static method. What happens to the class, is it now a static class and a non-static class, meaning there is a static version of the class with just the static method in memory and when you instantiate the class there will be an instance with all the non-static methods? I may be confusing myself. C# .net framework.
Non-static class with static and non-static method.
public class Class1
{
public static string Class1Method()
{
return "static";
}
public void Class1Method2()
{
//Not Static
}
}
Second class that would be using it.
public class Class2
{
public void Class2Method()
{
Class1.Class1Method();
new Class1().Class1Method2();
}
}
Class1 is considered non-static.
However, if you were to run say ReSharper over Class1 as it appears above, it may suggest to you to consider making it static because Class1 has no instance members. i.e. static class Class1 as well as public static void Class1Method2.
Otherwise, as it stands now, there is no point to making Class1Method2 an instance method because there are no instance members to act upon.

What's the functionality of a class has a static member of it self? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
An example:
class E
{
public static E e;
//...
};
What's the functionality of this or under which circumstances should we use this? Thanks.
One of usages can be to implement singleton (When you need a class that has only one instance, and you need to provide a global point of access to the instance): Implementing Signleton
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
A static variable cannot hold a reference to anything else that is declared in an instance, but rather a static variable/method belongs to the type instead of an instance of a type.
Consider this:
public class TestClass
{
private static string _testStaticString;
private string _testInstanceString;
public void TestClass()
{
_testStaticString = "Test"; //Works just fine
_testInstanceString = "Test";
TestStatic();
}
private static void TestStatic()
{
_testInstanceString = "This will not work"; //Will not work because the method is static and belonging to the type it cannot reference a string belonging to an instance.
_testStaticString = "This will work"; //Will work because both the method and the string are static and belong to the type.
}
}
The many usages are so many it could fill books. As someone mentioned, the Singleton pattern makes use of it.

How to make global variables? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In Windows application development using C# .NET, how do you make a global variable or global instance of a class, which can then be directly used by all other windows forms, e.g. form1, form2, etc.
You can create a static class and define a static variable inside it.
All the classes in your project can refer to it using MyGlobalVariables.GlobalVariable
public static class MyGlobalVariables
{
public static int GlobalVariable;
}
Create a public static class which holds the global variables
eg.
public static class GlobalValues
{
public static int UserId{get;set;}
}
Read more about C# Global Variable
Also I guess you should read about Classes and Structs
Create singleton class so that instace can be created once and used across application
public class Global
{
private static readonly Global instance = new Global();
public static Global Instance
{
get
{
return instance;
}
}
Global()
{
}
public string myproperty
{
get;set;
}
}
Usage:
Global.Instance.myproperty
Make it as a static variable and static class, e.g.
private static string foo = "this is static";
public static class Bar
{}

static keyword when creating instance

I came across the following code.
public class Test
{
public static Test Create()
{
return new Test
{
a1 =1,
b1="abc"
};
}
:
:
:
}
And in the calling class it is instantiated as below
static Test model = Test.Create();
What is the use of static keyword in the above line? What will be the difference if we don't use the static keyword? I'm using .NET 4 and VS 2010
EDIT
I know what is static in c#. The main reason I asked this question is why is it used when creating instance of class?
In this concrete presented code, don't see much sence of using this technique, but usually
you can do this in order to control your type instances creation.
For example: immagine that your class interacts with some COM object of the client, that can not be instantiated more the 10 times. To control that consumer of your API will not create more then 10 instances of your type, you can use this technique.
public class MyComWrapper {
private MyComWrapper () {} // MAKE CTOR PRIVATE SO NOONE CAN CREATE
// AN INSTANCE OF YOUR CLASS IF NOT WITH
// `static` METHOD CALL
static int counter = 0; //INSTANCE COUNTER
public static MyComWrapper Create()
{
if(counter >10) //MORE THEN 10, BAD !
throw new InvalidOperationException("Can not instantiate more then 10 instances");
counter ++;
return new Test
{
a1 =1,
b1="abc"
};
}
}
The static keyword makes it available without instantiating the object. The author is creating a function to instantiate the object in a specific way, but since it's the default constructor anyone can instantiate it.
Although not exclusively, along with making the constructor private, this is a pattern commonly used in the Singleton Pattern.
Static modifier belongs to the type itself rather than to a specific object.
You don't have to create an instance to use that static function. you can directly use the static function without creating an instance of the class.
If the static keyword is applied to a class, all the members of the class must be static.
It is simple. They are separate uses of static. The first one creates a static method in a non-static class. The second one create a static member of the "calling" class.
Your Test class itself is not static, so you are allowed to instantiate it.
To answer your question: if you do not use the static keyword in the calling class, it will be a "normal" instance member.

Extension methods on a static class? [duplicate]

This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
I know i can do the below to extend a class. I have a static class i would like to extend. How might i do it? I would like to write ClassName.MyFunc()
static public class SomeName
{
static public int HelperFunction(this SomeClass v)
You can't have extension methods on static classes because extension methods
are only applicable to instantiable
types and static classes cannot be
instantiated.
Check this code..
public static bool IsEmail(this string email)
{
if (email != null)
{
return Regex.IsMatch(email, "EmailPattern");
}
return false;
}
First parameter to IsEmail() is the extending type instance and not just the type itself. You can never have an instance of a static type.
You can't extend static classes in C#. Extension methods work by defining static methods that appear as instance methods on some type. You can't define an extension method that extends a static class.
You might want to turn your static class into a singleton. Then there will only be one instance of the class. And you can use extension methods on it because it's an instance.
This is provided you have access to the source code of the class.

Categories

Resources