So i have nested type classes that go something like this:
namespace MyNamespace
{
public class User
{
private int id = 0;
private string userId = "";
private string userPassword = "";
public int Id
{
get { return id; }
set { id = value; }
}
public string UserId
{
get { return userId; }
set { userId = value; }
}
public string UserPassword
{
get { return userPassword; }
set { userPassword = value; }
}
public User()
{
id = 0;
userId = "";
userPassword = "";
}
public static class SignonInfo
{
private static string sesstoken = "";
private static DateTime sessstart = new DateTime();
public static string SessToken
{
get { return sesstoken; }
set { sesstoken = value; }
}
public static DateTime SessStart
{
get { return sessstart; }
set { sessstart = value; }
}
}
}
}
My end goal here was to be able to access the nested static class like this:
User user = new User();
string token = user.SignonInfo.SessToken;
I'm trying to avoid instantiating the class like this:
User.SignonInfo user = new User.SignonInfo()
I need to be able to access properties of both User and SignonInfo classes.
Could someone help me to get on track or slap me about and tell me i'm doing it all wrong?
TIA
The problem is that it's a static class, so an "instance" doesn't have access to it. This is a good thing, as it prevents global state from masquerading as a well-encapsulated object.
I'd suggest making the nested class non-static, and having theUser class create an instance as needed by the caller (maybe add a public SignonInfo GetSignonInfo() method.)
You are trying to access your nested class as if it were a member of the instance of the outer class.
Change
string token = user.SignonInfo.SessToken;
to
User.SignonInfo.SessToken;
Note, that you do not get an instance of the static nested type per outer instance, there is only one for the entire outer class.
Related
Hi there I am trying to create a terminal based application in C#. However I am getting confused. I have a list in memberrecord class, User is the parent class whereas admin & ProjectMember are its children. I want to be able to register a projectmember object by getting inputs from user; I want the new registered projectmember to be added in the list in memberrecord.
In the admin class I want to check if the register method is working fine and it is printing out the users list.
When I try to code it out and create a register method in User Parent class and try to print it, it is not printing and not showing up.
In which class should I create the regiter method? And also the print method?
public class UserRecord
{
private List<User> _users;
public UserRecord()
{
_users = new List<User>();
}
public List<User> Users
{
get { return _users; }
set { _users = value; }
}
public void AddUser(User u)
{
_users.Add(u);
}
public int NoOfUser()
{
return _users.Count;
}
public void PrintUser()
{
foreach (User u in _users)
{
Console.WriteLine(u.Id + u.Name);
}
}
public void RegisterUser()
{
ProjectMember projectMember = new ProjectMember();
System.Console.WriteLine("Enter ID:");
projectMember.Id = Convert.ToInt16(Console.ReadLine());
System.Console.WriteLine("Enter Name:");
projectMember.Name = Console.ReadLine();
System.Console.WriteLine("Type of member");
int input;
input = Convert.ToInt16(Console.ReadLine());
if (input == 1)
{
projectMember.MemberType = MemberType.Manager;
}
else
{
projectMember.MemberType = MemberType.Member;
}
Console.WriteLine(projectMember.Id + projectMember.Name);
UserRecord userRecord = new UserRecord();
userRecord.AddUser(projectMember);
}
}
and enum MemberType:
public enum MemberType
{
Manager, Member
}
And ProjectMember class:
public class ProjectMember : User
{
private MemberType _memberType;
public MemberType MemberType
{
get { return _memberType; }
set { _memberType = value; }
}
public ProjectMember(int id, string name, MemberType memberType) : base(id, name)
{
_memberType = MemberType;
}
public ProjectMember(){ }
}
and Admin class:
public class Admin : User
{
public Admin(int id, string name) : base(id, name)
{ }
}
and User class:
public abstract class User
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public User(int id, string name)
{
_id = id;
_name = name;
// _users = new List<User>();
}
public User(){ }
}
and Program class:
class Program
{
public static void Main(string[] args)
{
UserRecord userRecord = new UserRecord();
userRecord.RegisterUser();
userRecord.NoOfUser();
userRecord.PrintUser();
}
}
I am developing it further along. So I know I have to work in while loop in the main, but I wanted to test it along the way
I have this class that contains a static list
public class TypeList
{
public string Name;
public string NameTag;
public TypeList(string Name, string NameTag)
{
this.Name = Name;
this.NameTag = NameTag;
}
public static List<TypeList> DataType = new List<TypeList>() {
new TypeList("DataType","-1"),
new TypeList("OpOne","1"),
new TypeList("OpTwo","2"),
};
}
I then put the static list called DataType into a combobox:
public void RefreshList()
{
List<TypeList> data = new List<TypeList>();
data = TypeList.DataType;
typeCB.DataSource = data;
typeCB.DisplayMember = "Name";
typeCB.ValueMember = "NameTag";
typeCB.SelectedValue = -1;
typeCB.SelectedText = "Select DataType";
}
However, when I run it, all I get are the classnames in my combobox. Is something wrong with my code? I tried to do
data.Select(x=>x.Name).ToList()
But that just gives me the name portion.
I might be wrong, but based on the Documentation and Example it might be that this Feature only works with public property getters, not public fields:
Gets or sets the property to display for this ListControl.
public class USState
{
private string myShortName;
private string myLongName;
public USState(string strLongName, string strShortName)
{
this.myShortName = strShortName;
this.myLongName = strLongName;
}
public string ShortName
{
get
{
return myShortName;
}
}
public string LongName
{
get
{
return myLongName;
}
}
}
Of course I would also advise against making the list a part of the Type class. A simple Programm scope static would be better. If that is the case and as autoproties have have become a thing by now, this should be enough of a fix:
public class Type
{
public string Name { private set; get } ;
public string NameTag {private set; get };
public TypeList(string Name, string NameTag)
{
this.Name = Name;
this.NameTag = NameTag;
}
}
//use in the class of main, the form or some similar central point
static List<Type> TypeList = new List<Type>();
Hopefully this makes sense. I have a class named ShippingCont
In this class, I have a LINQ connection like below. I want to be use this class to call the given table and get all the necessary fields instead of calling individual queries to the DB.
public static ShippingContainerDataContext shippingContainer = new ShippingContainerDataContext();
public static SHIPPING_CONTAINER sc2 = shippingContainer.SHIPPING_CONTAINERs.FirstOrDefault(a => a.CONTAINER_ID == _externalContainerId);
private string _containerId = sc2.COMPANY;
private string _company = sc2.COMPANY;
public string fromProgram
{
get { return _externalContainerId; }
}
public string ContId
{
get { return sc2.CONTAINER_ID; }
set { _externalContainerId = value; }
}
public string _ContainerId
{
get { return sc2.CONTAINER_ID; }
set { _ContainerId = value; }
}
public string _Company
{
get { return sc2.COMPANY; }
set { _company = value; }
}
When I try to pass a value to the _externalContainerId in the class. The LINQ query returns no records and I get the error Object reference not set to an instance of an object.
I know the LINQ returns data because when I manually provide the container ID in the LINQ query like (see below), I get a result set.
public static SHIPPING_CONTAINER sc2 = shippingContainer.SHIPPING_CONTAINERs.FirstOrDefault(a => a.CONTAINER_ID == "00008878742000004419");
The value is being pass from the main program like below.
ShippingCont sc = new ShippingCont("00008878742000004419");
I know the value is being passed because when I call the fromProgram() the value prints.
What am I doing wrong?
Since sc2 is static, the query is probably running before _externalContainerId is set (_externalContainerId = null), which would return empty. It would then remain empty for the duration of the program, because it is not getting recalculated, causing an error when you try to access a member. Since you are setting _externalContainerId in the constructor, you might place the assignment of sc2 in there as well. E.g.
public ShippingCont(string id)
{
this._existingContainerId = id;
sc2 = shippingContainer.SHIPPING_CONTAINERs.FirstOrDefault(a => a.CONTAINER_ID == _externalContainerId);
}
public static ShippingContainerDataContext shippingContainer = new ShippingContainerDataContext();
public SHIPPING_CONTAINER sc2;
private string _containerId = sc2.COMPANY;
private string _company = sc2.COMPANY;
public string fromProgram
{
get { return _externalContainerId; }
}
public string ContId
{
get { return sc2.CONTAINER_ID; }
set { _externalContainerId = value; }
}
public string _ContainerId
{
get { return sc2.CONTAINER_ID; }
set { _ContainerId = value; }
}
public string _Company
{
get { return sc2.COMPANY; }
set { _company = value; }
}
I am new in programming and trying to learn singleton but stuck in somewhere.
Here is my user class:
public class User
{
private static User user;
private User()
{
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string isim;
public string Isim
{
get { return isim; }
set { isim = value; }
}
private string soyad;
public string Soyad
{
get { return soyad; }
set { soyad = value; }
}
public static User CreateUser()
{
if (user == null)
user = new User();
return user;
}
}
In my web form I tried this:
User myuser = User.CreateUser();
to create an object but it gives me an error like there is nothing as CreateUser()..What am I doing wrong
All you have to do is like following:
You have to modify The User class to make it like this
public class User
{
public int Id { get; set; }
public string Isim { get; set; }
public string Soyad { get; set; }
public class User(){}
public User(int id, string isim, string soyad)
{
Id = id;
Isim = isim;
Soyad = soyad;
}
}
Then you implement Singleton (user buisiness logic) class like this
using System;
public sealed class UserBusiness
{
private static volatile UserBusiness instance;
private static readonly object syncRoot = new Object();
private UserBusiness() { }
public static UserBusiness Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new UserBusiness();
}
}
return instance;
}
}
public void AddUser(User userToAdd)
{
//TODO use your ORM or whatever to acces database and add the user
//for example if you use entityFramework you will need to do
//Context.Customers.Add(user)
//Context.SaveChanges();
//Just For Example
}
}
There are many implementation of singleton like mentioned in this MSDN article
and finally in your webForm Code you put the following :
var newUser = new User(1, "user1Isim", "user1Soyad");
UserBusiness.Instance.AddUser(newUser);
After All, there are many ways to do this, depends on your needs. I found this as the simpliest way to explain.
I've no experience of using C# but as part of one of our college modules we have to create a slot machine application. We created a Gambler class and I have to make a CheckBalance class where I will call the Token method from the Gambler class. But I get the error that is mentioned in the thread title.
Int tokens = Gambler.Tokens;
The above line is where I am getting my error.
This is my code:
enter code herenamespace CasinoClasslibrary
{
public class Gambler
{
public string Name { get; private set; }
public int Age { get; private set; }
public long CreditCardNum { get; private set; }
public int Tokens { get; public set; }
public string Username { get; private set; }
public string Password { private get; public set; }
public Gambler(string Name, int Age, long CreditCardNum, int Tokens, string Username, string Password)
{
this.Name = Name;
this.Age = Age;
this.CreditCardNum = CreditCardNum;
this.Tokens = Tokens;
this.Username = Username;
this.Password = Password;
}
}
public class Cashout : Gambler
{
public Boolean CheckBalance()
{
int tokens = Gambler.Tokens;
return true;
}
}
}
Since you are inheriting from Gambler I suspect that you need to access base.Tokens like:
public Boolean CheckBalance()
{
int tokens = base.Tokens; //here
return true;
}
Otherwise since Toakens is an instance member you have to create object of Gambler and then access it.
There are other errors in your code as well. You haven't defined a default (parameter less) constructor in your base class and you need to call the existing base constructor in your child class.
public class Cashout : Gambler
{
public Cashout()
: base("",0, 0, 1, "", "") //something like this
{
}
public Boolean CheckBalance()
{
int tokens = base.Tokens;
return true;
}
}
Because Cashout inherits from Gambler you can just do this. This is because the Cashout instance will have a Tokens property as well.
public class Cashout : Gambler
{
public Boolean CheckBalance()
{
int tokens = Tokens;
return true;
}
}
However, if you intended the method to be static, you will need an instance of Gambler to access that property and this should be passed into the static method as such.
public class Cashout : Gambler
{
public static Boolean CheckBalance(Gambler myGambler)
{
int tokens = myGambler.Tokens;
return true;
}
}
Finally, if you intended this Tokens property to be static itself, you need to declare it as such
public static int Tokens;
You may also want a static constructor to set it up.
Tokens is not static method but you try to access it through static construct (class level).
can make this work by declaring it static (although that's not likely what you want)
public static int Tokens { get; public set; }
or by instantiating Gambler
new Gambler().Tokens;