Static Operation like java in c# - c#

In java you can add static operation block in any class and it will be called when the application start:
class test{
static{
//do some operation when the application starts.
}
}
What is the equivalent in c#?
Thanks

C# has the static constructor:
class Test {
static Test() {
// …
}
}

The equivalent in C# is the static constructor:
class Test
{
static Test()
{
//do some operation before accessing to any member of the class
}
}
The static constructor is guaranteed to be executed before any class member is accessed. It's not guaranteed to be called at application start though.

It's called a static constructor:
class test
{
static test()
{
//do some operation when the application starts.
}
}

Use static constructor
class test
{
static test()
{
// do some job
}
}

If I recall properly it's not easy, you have to resort to static contructors.
Try to take a look here Microsoft documentation

Related

Is it possible from getting a public void from another C# file?

I'm quite new to C#, and I'm using it for coding a game on Unity. I have a file named GameTools.cs that helps me with commands so that I don't have to do too much. It basically makes my code simpler and shorter. Now with the code...
//GameTools.cs
public void DoSomething() {
//some code
//some more code
}
And inside my file IntroBehavior.cs has the same void as shown above.
//IntroBehavior.cs
void Start() {
DoSomething(); //command shown above
}
Will this work? Do I have to specify something inside IntroBehavior that will be able to run code from GameTools?
in c# all functions belong to classes. They are either instance methods, or static
Instance methods operate in instances of the class
public class User{
void Login(); <<< === instance method
}
used like this
var u1 = new User();
u1.Login();
Static methods dont operate on instances of classes
public class User{
static User CreateUser(); <<<<<= static
Login(); <<< === instance method
}
Here you use them like this
var u2 = User.CreateUser();
See that you can mix the 2. If you only want static methods in a class (to be sure ) then do
public static class User{
static CreateUser(); <<<<<= static
//Login(); <<< not allowed
}
So you want
static public class GameTools{
public static void CallSomething() {
//some code
//some more code
}
}
Now in you other file
void Start() {
GameTools.CallSomething(); //command shown above
}
Of course that method has to be in a class too.

In C# [AttributeUsage(AttributeTargets.Parameter)] Is not working

While creating a custom attribute of "AttributeTargets.Parameter" constructor is not called. I want to use the parameter value of Fn function under Test Class. I used .net core and .net standard.
class Program
{
public static void Main()
{
var test = new Test();
test.Fn("Hello");
Console.WriteLine("end");
Console.Read();
}
}
public class Test
{
public void Fn([Parameter] string parm)
{
Console.WriteLine(parm);
}
}
[AttributeUsage(AttributeTargets.Parameter)]
public class ParameterAttribute : Attribute
{
public ParameterAttribute()
{
Console.WriteLine("In Parameter Attribute");
}
}
As far as I remember, Attribute constructors are only executed when you start inspecting the type and not when an instance of that type is created or a method executed (in your case).
You can take a look at this answer for a detailed example of the order of execution when using custom Attributes.
Hope it helps!

Error - the program is not giving output while calling the print method

This is a simple program I created - one table class, one main class. In the table class I created a print method which simply outputs my name. From the main class I am calling the print method but not getting the output.
namespace ConsoleApplication3
{
class table
{
public static void print()
{
Console.WriteLine("My name is prithvi-raj chouhan");
}
}
class Program
{
public static void Main()
{
table t = new table();
t.print(); // Error the program is not giving output while calling the print method
}
}
}
Since the function you are calling is static.
Use this syntax
public static void Main()
{
table.print();
}
Quote from MSDN:-
A static method, field, property, or event is callable on a class even
when no instance of the class has been created. If any instances of
the class are created, they cannot be used to access the static
member. 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; for
instance, a math library might contain static methods for calculating
sine and cosine.
print is a static method, so call it as a static method:
public static void Main()
{
table.print();
}
try this:
class Program
{
public static void Main()
{
table.Print();
}
}
Print(); is a static method so you dont need to instantiate a new Table object in order to access it's methods
You are calling print() as an instance method but it is static. Try to remove the static keyword from the method.
Try to add a Console.ReadLine(); after table.print();.
UPDATE:
Missed the part with static, now corrected.

OOP - how to call a function before the class constructor

I have a job interview tomorrow and I'm trying to answer this question:
There is a class named C and method m in this class, this class have also empty constructor:
Main ()
{
C c = new c();
}
Class C {
public c {
//empty constructor
}
public m {
//does something - doesnt mind
}
}
And what you have to do is to change the code so that in a creation of an instance class C, the method m would be called before the class constructor.
You have to do this without changing the main (edit only the class code).
Thanks in advance!
Like the other answers have said, you can make the method static. But then you need to explicitly call it. If you make a static class constructor, that will get called once automatically (you don't need to call it), the first time the class is referenced (like when you construct the first instance). You can't exactly control when it executes, but it will execute before the first instance is constructed. Based on the way they've worded the question (you can't change the Main method), I think static class constructor is the answer they're looking for.
http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx
Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created or any static members are
referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
Java doesn't have static class constructors, but they do have static initialization blocks..
static {
// code in here
}
To call a class's method before its constructor gets called you either have to turn this method into static so you don't need an instance of that class to call it, or (in C#) you can use FormatterServices.GetUninitializedObject Method to get an instance of your class without running the constructor (which of course may not be a wise thing to do).
In JAVA:
make method static and call your method in static block.
class C{
static{
m();
}
public C() {
System.out.println("Constructor Called..");
}
public static void m() {
System.out.println("m() is called.");
}
}
Main call
public static void main(String[] args) {
new C();
}
In both Java and C# you can use, base class constructors, static constructors (Edit: static initializer block in Java), and field initializers, to call code before the C class's constructor executes without modifying Main.
An example using a field initializer block in Java:
class C {
{ m(); }
public C() {
System.out.println("cons");
}
public void m() {
System.out.println("m");
}
}
This prints "m", then "cons". Note that m is called every time a C is constructed. A static initializer block would only be called once for the JVM.
Its basic OOP. You have to make a public static method and call it. That method can then call the constructor, or you can call the constructor directly from main.
Before you call the constructor, the object don't exist, therefore no instance methods exist, therefore nothing tied to the instance/object can be called. The only things that do exist before the constructor is called is the static methods.
Following way seems to achieve what is required. Without using static methods/variables
namespace FnCallBeforeConstructor
{
static void Main(string[] args)
{
MyClass s = new MyClass();
Console.ReadKey();
}
partial class MyClass: Master
{
public override void Func()
{
Console.WriteLine("I am a function");
}
public MyClass()
: base()
{
Console.WriteLine("I am a constructor");
}
}
class Master
{
public virtual void Func() { Console.WriteLine("Not called"); }
public Master()
{
Func();
}
}
}
Output is:
I am a function
I am a constructor

Static code blocks

Going from Java to C# I have the following question:
In java I could do the following:
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}
I know I can initialize this from the constructor but this does not fit my needs (I want to initialize and call some utility functions without create the object).
Does C# support this? If yes, how can I get this done?
Thanks in advance,
public class Application
{
static int attribute;
static Application()
{
attribute = 5;
} // removed
}
You can use the C# equivalent static constructors. Please don't confuse it with a regular constructor. A regular constructor doesn't have a static modifier in front of it.
I am assuming your //... rest of the code need to be also run once. If you don't have such code you can just simply do this.
public class Application
{
static int attribute = 5;
}
You just can write a static constructor block like this,
static Application(){
attribute=5;
}
This is what I could think of.
In your particular scenario, you could do the following:
public class Application {
static int attribute = 5;
// ... rest of code
}
UPDATE:
It sounds like you want to call a static method. You can do that as follows:
public static class Application {
static int attribute = 5;
public static int UtilityMethod(int x) {
return x + attribute;
}
}
I find something else useful. If your variable needs more than one expressions/statements to initialize, use this!
static A a = new Func<A>(() => {
// do it here
return new A();
})();
This approach is not limited on classes.
-A static constructor doesn't have any parameter.
-A static class can contain only one static constructor.
-A static constructor executes first when we run the program.
Example:
namespace InterviewPreparation
{
public static class Program
{ //static Class
static Program()
{ //Static constructor
Console.WriteLine("This is static consturctor.");
}
public static void Main()
{ //static main method
Console.WriteLine("This is main function.");
Console.ReadKey();
}
}
}
Output:
This is static constructor.
This is main function.

Categories