Home > OS >  I am getting an error "Type conflicts with the imported type
I am getting an error "Type conflicts with the imported type

Time:07-25

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)

CodePudding user response:

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 called Users? 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.

CodePudding user response:

I created an example that is similar to your example and does what you want.

    public class User
    {
        public int Id { get; set; }
        public int Cityid { get; set; }
        public bool Active { get; set; }
       
        private User GetUserForEdit(int id)
        {
            return new User()
            {
                Id = id,
                Active = true,
                Cityid = 1
            };
        }
        public void TestUser()
        {
            User user = GetUserForEdit(1); //creating an instance of a class within the class file itself.
            Console.WriteLine(user.Id   " "   user.Active   " "   user.Cityid);
        }
    }
 
        static void Main(string[] args)
        {
            User user = new User();
            user.TestUser();

            Console.ReadLine();
        }
  • Related