C# class not public - c#

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();
}
}
}

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;
}
}
}

Use string value from one class in another class

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.

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)
{
}
}

How to initialize a static property before initializing a static class?

Below Class2 has a property that needs to be set before GetSomething is called, however because I access Class2 at the top of Class1 the property is always null when it gets to Something class. I can't seem to figure out how to change my code to set the property before it's used. Anyone?
EDIT
I want to pass the dependency from form1's constructor, not hardcode it further up the chain.
public partial class form1
{
private static readonly ISomeConstructedClass someConstructedClass = Class1.SomeConstructedClass;
public form1()
{
someConstructedClass.SomeDependency = new SomeDependency();
someConstructedClass.Whatever();
}
}
public static class Class1
{
public static readonly ISomething something = (ISomething)Class2.GetSomething("something");
public static ISomeConstructedClass SomeConstructedClass
{
get
{
return something.SomeConstructedClass;
}
}
}
....
}
public class Class2
{
public static ISomeDependency SomeDependency
{
get;
set;
}
public static GetSomething(string something)
{
switch(something)
{
case "something":
return new Something( SomeDependency );
}
}
}
public class Something : ISomething
{
public ISomeDependency SomeDependency
{
get;
set;
}
public Something(ISomeDependency someDependency)
{
SomeDependency = someDependency;
}
}
[Re]Edit:
I was confused about what you were trying to do before, you just need to create the dependency first.
public partial class form1
{
private static /*readonly*/ ISomeConstructedClass someConstructedClass;
public form1()
{
Class2.SomeDependency = new SomeDependency();
someConstructedClass = Class1.SomeConstructedClass;
someConstructedClass.Whatever();
}
}
I would also move the creation of something into the property just to make sure it is not initialized too soon (before the form1 constructor is called).
public static class Class1
{
public static ISomething something;
public static ISomeConstructedClass SomeConstructedClass
{
get
{
if (something == null) {
something = (ISomething)Class2.GetSomething("something");
}
return something.SomeConstructedClass;
}
}
}
You can use a static constructor. This is called before any static (or instance for that matter) fields or methods are called/accessed.
Something like:
static Class2() {
SomeDependency = SomeDependencyYouNeed;
}
Why are you using static methods? It looks like you're attempting a sort of Dependency Injection. Either create an instance of Class2 and pass the dependency in the constructor (and don't use static methods), or pass the dependency as a parameter of the GetSomething() method.
public static GetSomething(string something, ISomeDependency dependency).

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