static keyword when creating instance - c#

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.

Related

Confused about public, static and private methods/classes/variables in C#

I'm a beginner in programming with C# and coming from a Python background.
I'm confused about the keywords public and static. Can someone please clarify the difference for me?
(Btw, I already know that Private variables/methods can never be accessed outside the function, whereas Public can be)
Here is just something I randomly tried to understand the difference between static, and non-static methods.
using System;
public class MainClass
{
public static void Main ()
{
int[] anArray = getAnArray();
foreach (int x in anArray)
{
Console.WriteLine (x);
}
MainClass m = new MainClass ();
foreach (int x in anArray)
{
m.Print(x);
}
}
public static int[] getAnArray()
{
int[] myArray = { 1, 2, 3, 4 };
return myArray;
}
public void Print(int x)
{
Console.WriteLine(x);
}
}
I understand that to use the non-static method Print, I first need to create an instance of the MainClass, then access the method by doing m.Print()
However I don't understand when exactly to use which. As far as I can see it would be a lot easier if Print was static, as I wouldn't need to create a new instance of my own function.
For eg, this would be simpler
private static void Print(int x)
{
Console.WriteLine (x);
}
And call the Print function with Print(x) instead of creating the instance of Main first.
So basically when to use what? When to use static or non-static in regard to not only methods but variables and even classes? (For eg when should I use public static class MainClass)
Small, self-explaining example of public/non-static and static methods in use:
Car car1 = new Car();
car1.setBrand("Ford"); //public non-static method
Car car2 = new Car();
car2.setBrand("Opel"); //public non-static method
Car.CompareParameters(car1, car2); //static method
Basically, non-static methods and properties describe objects of such class.
You can't call Car.setBrand() - non-static method using class name.
As a general rule of thumb:
Static methods
The static keyword makes the method directly accessible without having to create an instance of an object. As such, any state or side-effects it has will be static, ie "global". So only use static to create pure functions, ie methods that derive a return value from their inputs only, neither reading or writing state from outside the method.
The use of static is a trade-off between simplifying code and testing. The more side-effects you put in to a static method, the harder your code will be to test.
public methods
Anything marked public is accessible throughout your application. Marking something internal restricts it to just that assembly (you can view the term "assembly" as equivalent to a project in your solution") and private restricts it to only being assessable within a class/struct.
If you follow the principle of encapsulation, then the rule to follow is use private all the time, only using internal if you need to. And only use public if you really have to.
static members are class members, and shared between all instances of that class.
public methods/properties are available to other classes. It's possible to have a public static member which is available to other classes.
You can't access a non-static member from a static member.
If a function doesn't need access to any instance variables then it can be made static for a slight performance gain, but there are more useful ways to use static members.
Some uses for static off the top of my head:
Singletons (you create a protected constructor that is accessed by a static variable inside the class)
Console.WriteLine is static
Locks/semaphores (where there is only one available at the class level that is shared by all instances)
If something makes sense to be shared by all instances of a class, make it static

What is the meaning of static in differents parts of the code?

I have been learning C# for two weeks now, though it is not my first either second language. I have been wondering about the static word. I know I should have researched about this word long before...but this is the first time I realized how much confusing this word is for me. For what I have read:
A static class is a class which does not need to be instanciated to be used (
Class with single method -- best approach? ). This may have some advantages and some disadvanatges regarding testing, polymorphism etc.
But the static word can be applied also to classes, fields, methods, properties, operators, events and constructors !!! ( https://msdn.microsoft.com/en-us/library/98f28cdx%28v=vs.80%29.aspx ). Example:
Property:
private static string s = "";
Method:
public static void helperMethod() {
Console.WriteLine("Whatever");
}
Does the word static have a global meaning or employed in differents parts of the code the meaning can change?
class modifier
When static is applied to a class it indicates four attributes.
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
property or function modifier (and events and methods)
When applied to properties and functions, e.g.
public Thing
{
static int SharedCount { get; set; }
static string GenerateName()
{
// ...
}
}
it means that the properties and functions will be accessible via the type name, without instantiating the class. This properties and functions will not be accessible via an instance of the class. So, both
var i = Thing.SharedCount;
var s = Thing.GenerateName();
Are valid and correct statements, Where as
var i = new Thing().SharedCount;
var s = this.GenerateName();
are both incorrect.
Code in functions and properties declared with the static modifier cannot access non-static members of the class.
member variables
Member variables declared with a static modifier, e.g.
class Thing
{
private static int sharedCount = 0;
private static readonly IDictionary<string, int> ThingLookup =
new Dictionary<string, int>
{
{ "a", 1 },
{ "b", 2 }
};
}
are shared by all static functions and properties and by all instances of the class.
static constructors
When applied to constructors, e.g.
class Thing
{
static Thing()
{
\\ Do this once and first.
}
}
static means the constructor will run once per AppDomain, when the type is first accessed. There are special edge cases around this.
operators
When an operator is overloaded for a type, this is always declared as static, e.g.
public static Thing operator +(Thing left, Thing right)
{
// Something special to do with things.
}
It is not logical for this to be declared at an instance level since operators must apply to types.
These distinctions are explained here, here, here and here.
Static members are items that are deemed to be so commonplace that there is no need to create an instance of the type when invoking the member. While any class can define static members, they are most commonly found within utility classes such as System.Console, System.Math, System.Environment, or System.GC, and so on.
Also the static keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class. For example, a field that is marked as static can be accessed from all instances of that class through the class name.
Quick answer: No static remains the same contextually everywhere :
From dotnetperls:
These are called with the type name. No instance is required—this makes them slightly faster. Static methods can be public or private.
Info:
Static methods use the static keyword, usually as the first keyword or the second keyword after public.
Warning:
A static method cannot access non-static class level members. It has no this pointer.
Instance:
An instance method can access those members, but must be called through an instantiated object. This adds indirection.
C# program that uses instance and static methods
using System;
class Program
{
static void MethodA()
{
Console.WriteLine("Static method");
}
void MethodB()
{
Console.WriteLine("Instance method");
}
static char MethodC()
{
Console.WriteLine("Static method");
return 'C';
}
char MethodD()
{
Console.WriteLine("Instance method");
return 'D';
}
static void Main()
{
//
// Call the two static methods on the Program type.
//
Program.MethodA();
Console.WriteLine(Program.MethodC());
//
// Create a new Program instance and call the two instance methods.
//
Program programInstance = new Program();
programInstance.MethodB();
Console.WriteLine(programInstance.MethodD());
}
}
Output
Static method
Static method
C
Instance method
Instance method
D
In C#, data members, member functions, properties and events can be declared either as static or non-static.
Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
Static members are often used to represent data or calculations that do not change in response to object state.
Static can be used in following ways:
Static data members
Static constructor
Static Properties
Static methods
More references :
MSDN
Static
Static in c#
What is static ?
The static keyword means generally the same everywhere. When it is a modifier to a class, the class's members must also be marked static. When it is a modifier to a member, (fields, properties, methods, events etc.) the member can be accessed using the following syntax:
ClassName.memberName
Note that operators must be declared static and extension methods must be in a static class which means it also has to be static.
Word static speaks for itself. If you have something that may change for every new object of some type - it's instance member and if it stays the same for all instances - it's static member.
From MSDN :
It is useful to think of static members as belonging to classes and
instance members as belonging to objects (instances of classes).
Source : static and instance members
Static members can be accessed via class object, something like MyClass.MyMember when instance members are only accessible on instance of a class (new MyClass()).MyMember
It's obvious that compiler takes some time to create instance and only then you can access its properties. So instance members works slower than static members.
In simple words , static property is not being changed across the classes , if your static member is affecting multiple classes once you change the value of it, it will be changed in every single class that is being affected by it.
Static method has to be static if you tend to use it in a static context (static class or so..)
Static class is the one which cannot be instantiated, e.g. static class Car{} this car will always have the same properties ( colour, size...)
There are many concepts related to Static keyword.
This answer will resolve your confusion about static.

Is it safe for a class to create instances of itself inside the static constructor?

I stumbled upon a problem where i need an instance of the class inside its static constructor. I believed it was not possible to do it so i tried the following:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.someString);
Console.ReadLine();
}
}
class Foo
{
public static readonly string someString;
static Foo()
{
someString = new Foo().CreateString();
}
private string CreateString()
{
return "some text";
}
}
To my surprise, it works - the output is "some text". I believed the static constructor must run and complete before instances of the class can be created. This answer shows that this is not necessarily the case. Does this mean that static and instance constructors are independent of each other? And finally, is it safe to do this (create instances in static constructor)?
p.s. Let's ignore the fact that this can be avoided by using a different approach.
All that the specification says is that the static constructor will be called before any instance of the class is created. But it doesn't state anything about the fact that this constructor must finish:
A static constructor is used to initialize any static data, or to
perform a particular action that needs to be performed once only. It
is called automatically before the first instance is created or any
static members are referenced.
You could perfectly fine create instances of the class inside the static constructor and this is safe.
It is safe as it will be called only once.
Static constructor called automatically before the first instance is created or any static members are referenced any static fields are referenced. Hence when your application ran and you accessed Foo, the static constructor was executed and your string was initialized.
Is it safe ? : As such there is no harm in doing this. It is just they are executed only once.
For information on this read Static Classes and Static Class Members on MSDN

Differences between static class and instance class with private constructor

Although a static class has only one instance and can't be instantiated, a class with a private constructor can't be instantiated (as the constructor can't be seen), so every time you call this class, this is the same one instance?
Factory classes always follow the last convention (instance class with private constructor). Why is this?
Thanks
There's nothing stopping the class with the private constructor from having a public static method which returns instances of the class:
public class NoPublicConstructor
{
private NoPublicConstructor()
{
}
public static NoPublicConstructor NewInstance()
{
return new NoPublicConstructor();
}
}
As you can see, the static method does not return the same one instance.
edit: One of the reasons factory classes do this is to be able to separate responsibility in future versions: while your code always calls the factory creation method, the author may move all the "guts" out of that class into a different one and your code won't need to know the difference. Calling that class' (public) constructor ties it to an extent to the original class implementation.
You can't* get an instance from outside the class, but you can from inside. A static method or an inner class can create and return an instance of the class with a private constructor. The static class cannot be instanced by anything.
class Foo
{
private Foo()
{
}
public class Bar
{
public Bar()
{
}
public Foo GetFoo()
{
return new Foo();
}
}
}
..
Foo.Bar fooBar = new Foo.Bar();
Foo foo = fooBar.GetFoo();
Edit: *I use the term "can't" loosely. Brian Rasmussen pointed out in the comments to the OP that another method to obtain an instance is through a call through System.Runtime.Serialization.FormatterServices, and this is external to the class itself.
Foo foo = (Foo)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Foo));
Creating a class with private constructor is the common pattern for implementing a "Singleton" object.
The Singleton usually will instantiate an instance of itself, and only allow access to it through a static "Instance" property, which means there's only ever one instance of the class.
The advantage of using a Singleton over a purely static class is that you can utilize interfaces and different implementation classes within the singleton. Your "Singleton" might expose an interface for a set of methods, and you can choose which exact implementation class to instantiate under the covers. If you were using a purely static class, it would be hard to swap out a completely different implementation, without impacting other code.
The main downside of Singleton is that it's difficult to swap out the implementation class for testing, because it's controlled within the Singleton private methods, but there are ways to get around that.

How can a class have no constructor?

A while back I asked about instantiating a HttpContext object. Now that I have learnt what I didn't know, what confuses me is that you cannot say HttpContext ctx = new HttpContext(); because the object does not have a constructor.
But doesn't every class need a constructor? In C#, if you don't provide one, the compiler automatically provides a default cstr for you.
Also, if I have a string (example: "Hello There!") and I say Convert.ToBoolean("Hello"), or any string, how does this work? What happens behind the scenes? I guess a book like CLR Via C# would be handy in this case.
What am I missing?
Constructor can be private or protected.
Also you can't create instance of abstract class, even if that class has public constructor.
HttpContext has a public constructor with two overloads but it's not the default (no params) one.
As an example, you need to pass in a SimpleWorkerRequest instance in order to instatiate an HttpContext instance and assign it to HttpContext.Current:
//Initialize this stuff with some crap
string appVirtualDir = "/";
string appPhysicalDir = #"C:\Documents and Settings\";
string page = #"localhost";
string query = string.Empty;
TextWriter output = null;
//Create a SimpleWorkerRequest object passing down the crap
SimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);
//Create your fake HttpContext instance
HttpContext.Current = new HttpContext(workerRequest);
See this link for details.
Anyway some classes don't have public constructors - think of a singleton class for example, constructor is private (and you can call the static getInstance method to get current instance or create it if it is null).
Cheers
Singletons, for example, do not have constructors, or at least, no public constructors. So if your class is a singleton, instead of writing
MyClass c = new MyClass();
You would write instead
MyClass c = MyClass.getInstance();
You have 3 questions there...
HttpContext; it actually has two public constructors - but in reality you aren't expected to use them. In more general terms, you can use non-default constructors like so: MyType foo = new MyType("abc");.
Missing constructor
Fairly well covered already, but no: abstract / static are the simplest, but it also isn't necessary to have a public constructor.
ToBoolean
Behing the scenes, this will do the moral equivalent of bool.Parse("Hello"), which simply checks for known strings - in particular "True" and "False" (using OrdinalIgnoreCase, having dealt with null/trimming/etc).
I believe the HttpContext constructor has been marked private. That means that you cannot instantiate it yourself. The .net framework creates one for you behind the scenes...
Take a look at the Singleton Design Pattern.
In one word : static.
Otherwise, a class might be instantiated internally or privately (Factory or Singleton)
Signleton :
Class A{
public static readonly A Instance = new A();
private A()
{
}
}
If you make the constructor private, you cannot extarnaly instatiate a class. But within the class it is possible. So you can provide a static method that returns a instance of the class. The singleton pattern is based on this.
Compiler does not create
default constructor of a class until the class has constructor with arguments.
In HttpContext class , it has 2 constructors with arguments . So, error is shown when you do HttpContext obj = new HttpContext().
public class Sample
{
int x;
public Sample (int x)
{
x = 2;
}
}
public class Program
{
static void Main(string[] args)
{
Sample s = new Sample();//error is shown
}
}
When you remove The above constructor of Sample class , there will be no error because compiler creates default constructor (constructor with no arguments).

Categories

Resources