c# variable access from many different classes - c#

What is the common way to access a variable in c#, that is used by many different functions and classes?
Should you just pass this variable to every class/function that needs it or should you better create a new instance of the class, that holds the variable and access it inside the class/function that needs to call the variable?

It depends on on type of project and files hierarchy
One way is to create one Base class and inherit from it to every class your using
class BaseController
{
string connectionString = "..." //this is your often used variable
}
class UsersController : BaseController
{
Connect(connectionString);
//rest of class
}
class GroupsController : BaseController
{
Connect(connectionString);
//rest of class
}
Another way is to create class with static varibles if you can and call them without class instance
class MyVariables
{
static string connectionString = "..." //this is your often used variable
}
And call it like this
Connect(MyVariables.connectionString);
I think The second option is better

Related

Prevent a subclass of a singleton class from calling the singleton's constructor

Ok, I have a singleton class GraphMaster which contains a number of system-wide values. I have a subclass GraphObject : GraphMaster which has graph specific data. By subclassing, I can access members of either the global class or subclass. And by using a singleton class, I can change the global variables anywhere and have them be reflected in all the subclasses.
However, I'm getting stuck because the base class's constructor wants to call the singleton class's constructor, but it can't as it's marked private.
how do I get around this? Is what I'm trying to do possible? I went down this path due to responses to this post: Can I make a "global" object to store variables for multiple objects?
For example,
public class GraphMasterObject {
private static GraphMasterObject instance;
private GraphMasterObject() { }
}
public static GraphMasterObject Instance {
get {
if (instance == null) instance = new GraphMasterObject();
return instance;
}
}
public int globalVar=10;
}
public class GraphObject : GraphMasterObject {
public GraphObject() {
}
public int localVar=20;
}
I want to be able to do
GraphObject go = new GraphObject();
go.globalVar <- this is 10
GraphMasterObject.Instance.globalVar = 20;
go.globalVar <- now this is 20
Ok, I have a singleton class GraphMaster which contains a number of system-wide values. I have a subclass GraphObject : GraphMaster which has graph specific data.
That's a problem to start with. As soon as you have a class which has subclasses, that it by definition not a singleton. Someone can add another subclass at any point, and even if you only have one instance of each subclass, you'll have two distinct instances which are compatible with the base class.
You could add something in the base class constructor to throw an exception if there's already an instance, but it would be pretty smelly. Fundamentally, singletons are incompatible with subclassing. Rethink your design. (Ideally, avoid the singleton pattern in the first place, but that's another matter...)

Use SSIS Variable in another class besides ScriptMain.cs

I have a C# script task in SSIS that I can pass a variable to no problem. I have another class that I created in the script call otherclass.cs. How do I use the variable within otherclass.cs?
I tried to just do this:
_urlBase = Dts.Variables["User::URLBase"].Value.ToString();
But I get this error:
The name 'Dts' does not exist in the current context
I'm pretty new to C# and classes so I may not be asking the question correctly. Is what I'm asking even possible?
Thanks.
SOLUTION
Here is my solution to what I was trying to accomplish:
In ScriptMain.cs created new service like this:
OtherService ws = new OtherService(Dts.Variables["User::URLBase"].Value.ToString());
In the OtherService.cs I had this:
class OtherService
{
public OtherService(string urlBase)
{
_urlBase = urlBase;
//do other stuff
}
//other methods and stuff
}
When you add a C# Script Task in BIDS 2008, notice this line in the ScriptMain task that it generates for you:
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
This says that ScriptMain is a subclass of Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase. That base class (VSTARTScriptObjectModelBase) defines a member Dts of type Microsoft.SqlServer.Dts.Tasks.ScriptTask.ScriptObjectModel. This in turn has a member named Variables. That is what you are accessing when you type "Dts.Variables" in ScriptMain.
The class you define in "otherclass.cs" is not a subclass of VSTARTScriptObjectModelBase and therefore does not inherit its member Dts. That is why the compiler tells you "The name 'Dts' does not exist in the current context."
If otherclass needs access to a variable's value then as cfrag suggests you can pass this value in when you instantiate a member of your class or when you call the class member function that needs this value. If you will need to access multiple variables, consider something like this:
public otherclass(Microsoft.SqlServer.Dts.Runtime.Variables dtsVariables)
{
DtsVariables = dtsVariables;
// other stuff
}
private Microsoft.SqlServer.Dts.Runtime.Variables DtsVariables;
Now otherclass has an instance member named DtsVariables which its non-static members can use to access the Variables collection passed in when the object was created. You would instantiate it and call methods from ScriptMain like this:
otherclass oc = new otherclass(Dts.Variables);
string url = oc.MakeURL();
Inside otherclass.MakeURL(), you can use the instance variable DtsVariables like you would have used Dts.Variables in ScriptMain, e.g.:
public string MakeURL()
{
return DtsVariables["User::URLBase"].Value.ToString() + "/default.aspx";
}

delegating between classes - best practice

I have C# component that has a class as below:
namespace SharedComponent{
class TestResult {
//several members
}
}
In another existing C# application I am referencing this component and I need to instantiate this same class but with an additional identifier as below.
namespace ClientApplication {
class TestResult
{
//exact same members as above including methods
//actually the shared component class was created by gleaming
//that from this application!
int PersonID; //additional identifier
//not suitable to have in the shared component
}
}
In the client application there are several methods that rely on the additional identifier. So it is very tempting for me to emulate a copy constructor and create this object and fill in the additional parameter. This way I can use the existing functions as they are with minimal changes to the class.
Another way could be to add the rest of the details as a reference to the client side implementation.
namespace ClientApplication {
class TestResult {
SharedComponent.TestResult trshared = new SharedComponent.TestResult()
//but this warrants I have my class methods to delegate
//to the sharedcomponent throughout ; example below
internal bool IsFollowUp(ClientApplication.TestResult prevTest)
{
//a similar method is being used
//where a function takes the class object as parameter
trshared.IsFollowUp(prevTest.trshared);
}
int PersonID; //additional identifier
}
}
Which option is better? What is the best practice in this regard?
Environment: VS2008, C#, WinXP/Win7
It sounds to me like your ClientApplication.TestResult "is a" SharedComponent.TestResult. Assuming that SharedComponent.TestResult is not sealed, you can extend from that class. This way you do not have to copy paste code. If you are also able to modify SharedComponent.TestResult, then you can declare the methods to be virtual, and override their behavior in your ClientApplication.TestResult.
class TestResult : SharedComponent.TestResult
{
int PersonId { get; set; }
override bool IsFollowUp(ClientApplication.TestResult prevTest)
{
// Your own implementation or trivial (base.IsFollowUp(ClientApplication.TestResult.prevTest.trShared)
}
}
If you cannot change the method to be virtual in SharedComponent.TestResult, then you can use the keyword "new" in the derived class.

Is it possible to create nested classes in PHP as it is in C#?

In C# you can have nested classes like this, which are useful if you have classes which do not have meaning outside the scope of one particular class, e.g. in a factory pattern:
public abstract class BankAccount
{
private BankAccount() {}
private sealed class SavingsAccount : BankAccount { ... }
private sealed class CheckingAccount : BankAccount { ... }
public BankAccount MakeSavingAccount() { ... }
public BankAccount MakeCheckingAccount() { ... }
}
Is this possible in PHP?
I've read that it was planned for PHP 5, then cancelled, then planned again, but can't find definitive info.
Does anyone know how to create nested classes (classes within the scope of another class) as in the above C# example using PHP 5.3?
No, this isn't possible in PHP. Classes must inhabit the global namespace; the best you can do is just pretend they don't exist in all of your other code.
This kind of thing is common in PHP; for example, PHP lacks static initializers, so if you want to eagerly initialize the static members of a class, it must be done by calling a public method from outside the class. Ugly.

Accessing methods from another class in C#

I have a number of classes in a Classes file, and I want them all to be able to access the same, global method to save duplicating code. Problem is, I can't seem to access a method from another class in my file - any ideas?
So my class1.cs layout is similar to this:
public class Job1
{
public Job1()
{
}
}
public class Methods
{
public static void Method1()
{
//Want to access method here from Job1
}
}
You'll need to specify the class they are in. Like this:
public Job1()
{
Methods.Method1()
}
If the class Job1 is in a different namespace from Methods then you'll need to either add a using clause, or specify the the namespace when calling the method. Name.Space.Methods.Method1()
Actually. Public Job1(){} is a constructor and not a method. It can be called from main class by creating object form the JOB1 class. Here add the following code:
public static void method1()
{
Job1 j1=new Job1();
}
constructor can be invoked by creating a object to the corressponding class....
To access methods of other classes, the methods must be static with a public Access modifier.
static - Not bound to an instance of the class but shared by all other instances.
private - data can only be accessed from inside the same class.
public - data can be accessed from other classes but must be referenced.

Categories

Resources