Access static object from other instance - c#

I have a Program class which has:
private static ClientBase objClientBase = new ClientBase(new List<RecordType> { RecordType.none }, ModuleType.Monitor);
static void Main(string[] args)
{
objClientBase.Connect(); //IRRELEVANT
objQueueMon = new Main(); //<-INSIDE THIS IS WHERE I WANT TO ACCESS objClientBase
objClientBase.MainModuleThreadManualResetEvent.WaitOne(); //IRRELEVANT
}
This Progam creates a Main class instance as you see:
objQueueMon = new Main();
Notice that they are separated in different files, but the Main class instance is created inside the Program class.
Inside my Program class I want to access that objClientBase.
Do I have to create a constructor method and pass it or make a public access to it?
So what I want to achieve is, inside the Main class, do a objClientBase.FUNCTION

You can do exactly what you just said:
public class Main {
private ClientBase _caller;
public Main (ClientBase caller) {
_caller = caller;
}
}
Or, you can set it later
public class Main {
private ClientBase _caller;
public Main () {
}
// only your assembly sets it
internal SetClientBase(ClientBase cb) {
_caller = cb;
}
// but anyone gets it
// Now you can let some client execute "Function"
public ClientBase Caller {
{return _caller;}
}
}
Just an example

Change the constructor of your Main class to accept a ClientBase object, like this:
public class Main
{
private ClientBase _clientBase;
public Main(ClientBase clientBase)
{
_clientBase = clientBase;
}
public void SomeMethod()
{
// Use ClientBase.FUNCTION here
_clientBase.FUNCTION();
}
}

Related

Attribute to mark as "internal use"

I made a class which requires the public default constructor but
that is never called; instead another constructor is used at DataGrid.AddingNewItem.
I'd like to tell developers that the default constructor is not for their use.
Is there an attribute which suits the purpose?
I had checked DebuggerNonUserCode and MethodImplAttribute with MethodImplAttributes.InternalCall but not sure that's the proper approach.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.dataGrid1.CanUserAddRows = true;
var list = new List<RowX>();
this.dataGrid1.ItemsSource = CollectionViewSource.GetDefaultView(list);
this.dataGrid1.AddingNewItem += (s, e) => e.NewItem = new RowX("ABC");
}
}
public class RowX
{
public RowX()
{
//this is not used. but CollectionView require this to be public or
//CanUserAddRows doesn't work.
}
public RowX(object o)
{
//this is the actual ctor.
}
public string Text { get; set; }
}
Mark it private
class Foo
{
private Foo() {}
}
You can give your constructor an access modifier.
private This means it can only be called from another constructor in that class.
public class PrivateClass
{
//Only from inside this class:
private PrivateClass()
{
}
public static PrivateClass GetPrivateClass()
{
//This calls the private constructor so you can control exactly what happens
return new PrivateClass();
}
}
internal This means only code in the same assembly (i.e. from inside your library) can access it.
public class InternalClass
{
//Only from within the same assembly
internal InternalClass(string foo)
{
}
}

Create new instance of private class in another private class

Is it possible to create an instance of a private class in another private class? (Not counting within the main() program.)
And also, is it possible for a method in a private class to return a private type object?
This question came because I was following Scott Allen from PluralSight on C# Fundamentals With C#5. And on lesson 2 about classes and objects, he has a code example like this:
public GradeStatistics ComputeStatistics()
{
GradeStatistics stats = new GradeStatistics();
...
...
}
with GradeStatistics defined in a separate class file like:
class GradeStatisticss
{
}
Inlined comment: I am not talking about nested classes. What I meant is, you have two classes (separate files) and I am wondering if one class can create an instance of another class (knowing they are both private).
Edited with examples:
private class Example1
{
}
private class Example2
{
public Example1 DoSomeComputation()
{
return new Example1();
}
}
private class Example3
{
Example1 ex1 = new Example1();
}
Is Example3 able to create ex1? Can Example2 return a new instance of Example1?
Is it possible to create an instance of a private class in another private class?
Only if the private class for which you want to create an instance is declared inside the private class that wants to create the instance. If they are not nested, it's not possible.
Is it possible for a method in a private class to return a private type object?
Yes, it can.
Here's some code showing everything together:
public class Tester {
private class ThePrivateCreator {
private class TheOtherPrivateClass {
}
public Object createObject() {
return new TheOtherPrivateClass();
}
}
public void canWeDoThis() {
ThePrivateCreator c = new ThePrivateCreator();
Console.WriteLine(c.createObject());
}
}
class Program
{
public static void Main(string[] args) {
Tester t = new Tester();
t.canWeDoThis();
}
}
No. A private class cannot be accessed by another class in a different file. The reason why is that the modifier private is meant to encapsulate the data or method inside of that class. You should use the public or internal modifier if you want to access a class from a different class that is not nested. If it is nested, you can also use the protected modifier.
Not sure exactly what you had in mind, but here's one possible example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
private1 p1 = new private1();
private2 p2 = p1.foo();
Console.WriteLine(p2.Value);
Console.ReadLine();
}
private class private1
{
public private2 foo()
{
private2 p2 = new private2("I was created inside a different private class!");
return p2;
}
}
private class private2
{
private string _value;
public string Value
{
get { return _value; }
}
public private2(string value)
{
this._value = value;
}
}
}
}

Access to listbox in static method

I have one static method which I call from another class when I need update data in listbox. But then I need scroll listbox to last item. Here is code:
public static void updateMessages()
{
MyDatasCurentUser.Clear();//clear messages from previewous user from datas
foreach (var items in UniDB.returnlistOfMessagesData(IdOfChoosenUser, MainContentPage.myID))
{
_mydataCurentUser.Add(new BindingData
{
MessengerReadTime = new DateTime(items.readTime.Year, items.readTime.Month, items.readTime.Day, items.readTime.Hour, items.readTime.Minute, 0),
MessengeFullName = items.senderName,
MessengerTime = new DateTime(items.sendTime.Year, items.sendTime.Month, items.sendTime.Day, items.sendTime.Hour, items.sendTime.Minute, 0).ToString("dd.MM.yyyy - HH:mm"),
MessengerMessage = items.message,
MessengerIsFromMe = items.isFromMe,
});
}
lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
}
But I get error cannot access to non static field in static context at this: lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
Is there any way how I can do this lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last()); when is method updateMessages() called?
If you have a non static method of one class:
class Form1
{
public void UpdateMessages()
{
// ...
lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
}
}
And you want to call it from an object of a different class, that object will need a reference to the first object. A common solution is to pass the reference to the first object into the constructor of the second:
class OtherClass
{
Form1 _form;
OtherClass(Form1 form)
{
_form = form;
}
void Method()
{
//can access the methods of the other object
_form.UpdateMessages();
}
}
Alternatively you could pass the object in later:
class OtherClass
{
public void Method(Form1 form)
{
form.UpdateMessages();
}
}

Modify an attribute of a thread from other class

I have an problem with my code. I have 2 classes:
clsSMS
clsWorker
When my thread is running, I want to modify an attribute of them from my clsSMS class.
public class clsSMS
{
clsWorker objclsWorker;
public clsSMS(clsWorker objclsWorker = null)
{
this.objclsWorker.operatorBlocageError38();
// The above call doesn't work...
// I think the objclsWorker is always null...
// What do you think?
}
}
public class clsWorker
{
public clsSMS clsobjSMS;
public clsWorker(...)
{
this.clsobjSMS = new clsSMS(objclsWorker: this);
}
public void operatorBlocageError38(/*String port_concerne, bool erreur38*/)
{
MessageBox.Show("The method call work fine!");
}
}
It doesn't appear from the posted code that you ever instantiated clsWorker.
clsWorker worker = new clsWorker();
worker.operatorBlocageError38();
If you call operatorBlocageError38 before instantiating, the method has to be marked static.
public static void operatorBlocageError38()

How can I make one class solely responsible for creating and providing access to another class

This is how I understand I can implement the singleton pattern in C#:
public class ChesneyHawkes{
private static ChesneyHawkes _instance = new ChesneyHawkes();
public ChesneyHawkes Instance {get{return _instance;}}
private ChesneyHawkes()
{
}
}
What if I want to provide a single instance of an object, so that there can only ever be one, make the access to it public, but only allow it to be created or replaced by another singleton.
// The PuppetMaster should be the only class that
// can create the only existing Puppet instance.
public class PuppetMaster{
private static PuppetMaster_instance = new PuppetMaster();
public static PuppetMaster Instance {get{return _instance;}}
// Like a singleton but can be replaced at the whim of PuppetMaster.Instance
public static Puppet PuppetInstance {get {return Puppet;}}
private PuppetMaster()
{
}
public class Puppet{
// Please excuse the pseudo-access-modifier
puppetmasteronly Puppet(){
}
}
}
// To be accessed like so.
PuppetMaster.Puppet puppet = PuppetMaster.Instance.PuppetInstance;
You don't really need more than one singleton for that. Look at this example:
using System;
// interface for the "inner singleton"
interface IPuppet {
void DoSomething();
}
class MasterOfPuppets {
// private class: only MasterOfPuppets can create
private class PuppetImpl : IPuppet {
public void DoSomething() {
}
}
static MasterOfPuppets _instance = new MasterOfPuppets();
public static MasterOfPuppets Instance {
get { return _instance; }
}
// private set accessor: only MasterOfPuppets can replace instance
public IPuppet Puppet {
get;
private set;
}
}
class Program {
public static void Main(params string[] args) {
// access singleton and then inner instance
MasterOfPuppets.Instance.Puppet.DoSomething();
}
}

Categories

Resources