I have created a class file in C# called Users. I want to create an instance of a class from within the same class file. I thought had been able to do this in the past. When I try here. I get the message "The type Users in "" conflicts with the imported type "Users" in.
Is it possible to create an instance of a class within the class file itself. If so, can someone tell me what I am missing?
public class Users
{
public int ID { get; set; }
public int Cityid { get; set; }
public bool Active { get; set; }
public Users GetUserforedit(int id)
2
Answers
I see no reason why you couldn’t have an instance method of a class that returned an instance of the class itself, although it’s more common to make such a method a
static
method rather than an instance method.(In fact, if you couldn’t do that, you wouldn’t be able to have methods like
Clone()
!)As for your error messages, two possibilities occur:
The most obvious cause would be that there’s another class called
Users
in either the same namespace, or a namespace you’re importing. Do you have a web page calledUsers
? Another, earlier version of your class file, perhaps?The other possibility would be that your class not being within a namespace is somehow confusing the compiler. Try wrapping the class in a namespace, and see if you now get at least a more useful error message.
I created an example that is similar to your example and does what you want.