简体   繁体   中英

C# Runtime Error Declare a body because it is not marked abstract, extern, or partial

Hi I'm have some trouble making this tidbit of code run, as I'm getting a runtime error for Kennel.Kennel() must declare a body because it is not marked abstract, extern, or partial. Please advise and help if you can. Much appreciated.

using System;
using System.Collections.Generic;
using System.Text;

public class Kennel : IComparable<Kennel>
{
    private string _name;
    private string _breed;

    public string Name
    {

        get { return _name; }
        set { _name = value; }
    }

    public string Breed
    {
        get { return _breed; }
        set { _breed = value; }
    }

    public override string ToString()
    {
        return String.Format("Name: {0}, Breed: {1}", Name, Breed);
    }

    public Kennel();

    public Kennel(string name, string breed)
    {
        this._name = name;
        this._breed = breed;
    }

    #region #IComparable<Kennel> Members

    public int CompareTo(Kennel other)
    {
        return other.Name.CompareTo(this.Name);
    }

    #endregion

}


class Run
{
public static void Main()
        {
            List<Kennel> kennels = new List<Kennel>();
            kennels.Add(new Kennel("Alan", "French Bulldog"));
            kennels.Add(new Kennel("Larry", "English Terrier"));
            kennels.Add(new Kennel("Moe", "Gold Retriever"));
            kennels.Add(new Kennel("Curly", "Chihuahua"));

            foreach (Kennel k in kennels)
            {
                Console.WriteLine("Name: {0}, Breed: {1}", k.Name, k.Breed);
            }


            kennels.Sort();
            foreach (Kennel k in kennels)
            {
                Console.WriteLine("Name: {0}, Breed: {1}", k.Name, k.Breed);
            }


        }
}
public Kennel();

This doesn't make sense.

For an empty parameterless constructor, you still need a body:

public Kennel()
{}

You default constructor for Kennel has no implementation/body

Replace

public Kennel(); 

with

 public Kennel() {}

I'm guessing your error is on this line:

public Kennel();

You are declaring a method, but there is no implementation. Either remove it (that's what I'd do), or change it to:

public Kennel() {}

If your intent is to prevent people from constructing an object without providing the name and breed values, you can make this constructor private:

private Kennel() {}

So what do you not understand exactly? The constructor of Kennel must declare a body, what's not clear about that?

If you want the body to be empty, then go ahead and declare it empty:

    public Kennel() { }

You cannot NOT declare a body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM