Use string value from one class in another class - c#

I've got some methods in one class that return values of to,from,message and im trying to use these in the other class that has the default display message.
I can't seem to use the string values that I get from the methods in class 1 in class 2.
I have tried declaring the string values public but got overloaded with errors none of which really said why the error was happening.
public class ChristmasCard
{
public static void Main()
{
string toWhom = To();
string fromWhom = From();
double decorate = ChooseDecoration();
string message = AddMessage();
DoPromt(message);
DisplayMessage(decorate);
Console.ReadLine();
}
public class ChristmasCardTesting : ChristmasCard
{
public static void SantaA()
{
Console.WriteLine(ChristmasCard.toWhom);
Console.WriteLine(ChristmasCard.Message1);
Console.WriteLine(ChristmasCard.Message2);
Console.WriteLine(ChristmasCard.Message3);
Console.WriteLine(ChristmasCard.fromWhom);
Console.ReadLine();

I guess inheritance is not what you want here. You want to use an instance of your object instead.
First you want to create an instance of your ChristmasCard.
That instance should hold Properties/Fields of the values you like to hold in the RAM.
Then you want to create an instance of your ChristmasCardTesting and call the "testmethod" while giving the christmas card as parameter.
And that code could be executed in your Program.
I guess what you want to achieve should more like the following:
public class Program {
public static void Main(string[] args) {
ChristmasCard card = new ChristmasCard();
ChristmasCardController controller = new ChristmasCardController();
controller.SomeMethod(card);
WriteToConsole(card);
}
public static void WriteToConsole(ChristmasCard card) {
Console.WriteLine(card.ToWhom);
Console.WriteLine(card.Message);
Console.WriteLine(card.FromWhom);
Console.ReadLine();
}
}
/// <summary>
/// Pure data class does not needs methods!
/// </summary>
public class ChristmasCard {
public string ToWhom { get; set; }
public string FromWhom { get; set; }
public double Decorate { get; set; }
public string Message { get; set; }
}
/// <summary>
/// Controller for the dataClass
/// </summary>
public class ChristmasCardController {
public void SomeMethod(ChristmasCard card) {
card.ToWhom = To();
card.FromWhom = From();
card.Decorate = ChooseDecoration();
card.Message = AddMessage();
DoPromt(card);
DisplayMessage(card.Decorate);
}
private void DisplayMessage(double cardDecorate) {
//Write your message to the console
}
private void DoPromt(ChristmasCard card) {
//Do some ConsoleRead in here
}
private string AddMessage() {
throw new NotImplementedException();
}
private double ChooseDecoration() {
throw new NotImplementedException();
}
private string From() {
throw new NotImplementedException();
}
private string To() {
throw new NotImplementedException();
}
}
Edit:
If that is totally not what you want, please explain what you are trying to achieve and i'm 100% sure i'll find the answer.
Edit2
All methods from that Controller class could also be in the Program class.
Note these would have to be static if you move these methods. I hope this snipped makes it clear how to solve the problem.

Related

How can i Access a private variable in another class in C#

I wrote the code below and i want to access the private varibale in another class, i created instance of the class and tried to access it but couldn't. can someone point out what I did wrong in the code below?
using System;
namespace lab_first
{
public class AccessModifiers
{
private int Abc { get; set; }
private int bcd { get; set; }
}
class Program
{
static void Main(string[] args)
{
var acc = new AccessModifiers();
Console.WriteLine(acc.Abc)
}
}
}
You make members private so that nobody outside the class can access them.
This goes inline with the principle of information hiding.
Your example should look like this:
public class AccessModifiers
{
// You can only access this inside of the class AccessModifiers
private int Abc { get; set; }
internal void SetValue(int x){
// Access possible, because SetValue() is inside the same class
Abc = x;
}
internal int GetValue(){
// Access possible, because GetValue() is inside the same class
return Abc;
}
}
class Program
{
static void Main(string[] args)
{
var acc = new AccessModifiers();
// Abc is never modified directly, only indirectly.
acc.SetValue(5);
Console.WriteLine(acc.GetValue());
}
}
However, there is still a way to access the private member. It's called Reflection. However, note that private variables are considered an implementation detail and might change at any time, so you can't rely on it. E.g. someone might change the name from Abc to def and your Reflection-based approach fails.
You can either change private to internal or public in this case.
Another way is declaring the variables in the class as private and using C# Properties in the class to set and get the values of variables. this is called encapsulation which is a protective shield that prevents the data from being accessed by the code outside this shield).
public class AccessModifiers
{
private int _abc { get; set; }
private int _bcd { get; set; }
public int Abc
{
get
{
return _abc;
}
set
{
_abc = value;
}
}
public int Bcd
{
get
{
return _bcd;
}
set
{
_bcd = value;
}
}
}

string created from variable in c#

Is it possible to to define a string from a variable where the string does NOT have quotations. Example:
public class aclass
{
public string athing;
}
public void example(string thing)
{
aclass thing = new aclass();
}
The string thing can't be put into aclass thing = new aclass(); normaly.
Is there anyway to do it?
You need a constructor
void Main()
{
CreateExampleObject("testing");
}
public class Example
{
// This is a constructor that requires a string as an argument
public Example(string text)
{
this.Text = text;
}
public string Text { get; set; }
}
public void CreateExampleObject(string text)
{
Example example = new Example(text);
Console.WriteLine(example.Text);
}
You can do it this using many way but generally standard way is using constructor
please refer this link for better understanding.
C# : assign data to properties via constructor vs. instantiating
You have to ways of setting fields/property value of an object.
First is to do it through the constructor, as mentioned in other answer.
Second can be implmeneted in various ways:
Expose public property making field privte:
public class aclass
{
private string _athing;
public string Athing
{
get { return _athing; }
set { _athing = value; }
}
}
public void example(string thing)
{
aclass aclass = new aclass();
aclass.Athing = thing;
}
Or even shorter, you could use property:
public class aclass
{
public string Athing {get; set; }
}
Using your implementation, you make your field public, so you can set it easily:
public void example(string thing)
{
aclass aclass = new aclass();
aclass.athing = thing;
}
But it doesn't comply with OOP encapsulation principle.

How correctly to pass data from Singleton

I have Singleton class that get's data from web. And i need to pass those data to classes FirstDerived and SecondDerived. In this case is my class Singleton anti-pattern? Is it normal to use Aggregation relationship between DataSocket and FirstDerived, SecondDerived. Maybe it exist better object oriented solution?
namespace WpfApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new TestViewModel();
}
}
public class TestViewModel
{
public ObservableCollection<Base> Items { get; set; }
public TestViewModel()
{
DataSocket.Instance.SendDataAsync();
Items = new ObservableCollection<Base>();
Items.Add(new FirstDerived(1, DataSocket.Instance));
Items.Add(new SecondDerived(2, DataSocket.Instance));
}
}
public abstract class Base
{
}
public class FirstDerived : Base, IDisposable
{
public FirstDerived(int id, DataSocket socket)
{
socket.Client += ProcessDataFromSocket;
}
public void ProcessDataFromSocket(string arg)
{
Console.WriteLine("First Derived getting data: {0}", arg.ToString());
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class SecondDerived : Base, IDisposable
{
public SecondDerived(int id, DataSocket socket)
{
DataSocket.Instance.Client += ProcessDataFromSocket;
}
public void ProcessDataFromSocket(string arg)
{
Console.WriteLine("Second Derived getting data: {0}", arg.ToString());
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public sealed class DataSocket
{
private static DataSocket instance;
public delegate void Messages(string info);
public event Messages Client;
private DataSocket()
{
}
public void SendDataAsync()
{
Action Send = new Action(SendData);
IAsyncResult result = Send.BeginInvoke(null,null);
}
public void SendData()
{
while(true)
{
if (Client != null)
{
System.Threading.Thread.Sleep(3000);
Client("Test");
}
}
}
public static DataSocket Instance
{
get
{
if (instance==null)
{
instance = new DataSocket();
}
return instance;
}
}
}
}
To me it looks like DataSocket is the class that deals with networking, so any code to interact with the network should go there. Don't pass it into a constructor.
Rather, do something more like this sequence;
DataSocket.Instance.SendDataAsync();
Items = new ObservableCollection<Base>();
var data1 = await DataSocket.ReadData();
var data2 = await DataSocket.ReadData();
Items.Add(new FirstDerived(1, data1));
Items.Add(new SecondDerived(2, data2));
This way, your classes don't take a dependency on a global, constantly-changing object.
You might also want to consider some kind of lock statement to make sure that different parts of the code -- say, many different simultaneous web requests -- can't interfere with each other.

C# class not public

I am trying to make a class so when I do the following inside a file:
Functions LoginFunctions = new Functions();
LoginFunctions.loadFunctions();
It will create my object which I need, and make it public so every form which calls the class will be able to use it. The class file is below.
namespace App
{
public class Functions
{
public void loadFunctions()
{
TaskbarItemInfo taskbarItemInfo = new TaskbarItemInfo();
}
}
}
It doesn't seem to be making the taskbarItemInfo object public, and it is not letting me use it anywhere else other then inside the class. How do I make it public so every file that calls the class can use the object?
As the others have mentioned, make it a property, for example like so:
public class Functions
{
public TaskbarItemInfo TaskbarItemInfo { get; private set; }
public void loadFunctions()
{
this.TaskbarItemInfo = new TaskbarItemInfo();
}
}
Your taskbaritem class is in the scope of the method and therefore you wont be able to access it outsite of the class.
Create a public property or return it in the method.
namespace App
{
public class Functions
{
private TaskbarItemInfo _taskbarItemInfo;
public TaskbarItemInfo taskbarItemInfo
{
get
{
return _taskbarItemInfo;
}
}
public void loadFunctions()
{
_taskbarItemInfo = new TaskbarItemInfo();
}
}
}
I would also go and change the loadFunctions method to a constructor which creates all the objects you need.
public Functions()
{
_taskbarItemInfo = new TaskbarItemInfo();
}
In the example you provide, taskbarItemInfo is declared within the local scope of the loadFunctions() method. If you want it to be public for some class, you must make it a class member before you can make it public.
You need to make the variable public.
namespace App
{
public class Functions
{
public TaskbarItemInfo TaskbarItemInfo { get; private set; }
public void loadFunctions()
{
TaskbarItemInfo = new TaskbarItemInfo();
}
}
}
EDIT: You could also do the initialization of the items in the constructor.
namespace App
{
public class Functions
{
public TaskbarItemInfo TaskbarItemInfo { get; private set; }
public Functions()
{
loadFunctions();
}
private void loadFunctions()
{
TaskbarItemInfo = new TaskbarItemInfo();
}
}
}
Then you don't need the LoginFunctions.loadFunctions(); line of code after you initialize your LoginFunctions object.
You probably want to access it as a property which generates a private static member when needed.
namespace App
{
public class Functions
{
private static TaskbarItemInfo _taskbarItemInfo;
public static TaskbarItemInfo TaskBarItemInfoProperty
{
get{
if (_taskbarItemInfo == null)
{
_taskbarItemInfo = new TaskbarItemInfo();
}
return _taskbarItemInfo;
}
}
}
public class Test
{
public void testFunction()
{
Functions.TaskBarItemInfoProperty.doSomething();
}
}
}

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