Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to class C#?

Tags:

c#

.net

static

I have code as below

public  class LocalDB
{
    public static int e_SessionID;

    public static string e_EventName;

    public static string e_TimeCreate;
}

in other class:

public static LocalDB newEvent ;
public void something()
    {
      newEvent.e_SessionID=123;
    }

but it is can not pass value.

like image 359
user3409461 Avatar asked Mar 17 '14 08:03

user3409461


People also ask

How do you pass an argument to a class in C#?

In C#, arguments can be passed to parameters either by value or by reference. Remember that C# types can be either reference types ( class ) or value types ( struct ): Pass by value means passing a copy of the variable to the method. Pass by reference means passing access to the variable to the method.

Can I pass var as parameter in C#?

It means we cannot pass a variable value as input using out parameter. Variables passed as out arguments do not have to be initialized before being passed in a method call. Even if it is initialized, this value cannot be accessed inside the method.

How do you pass parameters to a constructor?

Arguments are passed by value. When invoked, a method or a constructor receives the value of the variable passed in. When the argument is of primitive type, "pass by value" means that the method cannot change its value.


2 Answers

Problem : You are trying to access the static feilds using instance reference variable newEvent as below:

newEvent.e_SessionID=123;
//^^^Here

Solution : You need to use classname to access the static fields

newEvent.e_SessionID=123;
//^^^Replace with classname LocalDB here

Replace this:

 newEvent.e_SessionID = 123;

With this:

LocalDB.e_SessionID = 123;
like image 105
Sudhakar Tillapudi Avatar answered Sep 23 '22 22:09

Sudhakar Tillapudi


Why don't you set them up as properties? Have a read of this SO post why prefer properties to public variables

"Fields are considered implementation details of classes and exposing them publicly breaks encapsulation."

public class LocalDB
{
    public int SessionID { get; set; }
}
like image 23
Paul Zahra Avatar answered Sep 23 '22 22:09

Paul Zahra