简体   繁体   中英

How to implement an interface member correctly?

I am coding a simple application that works with collections. How do I properly implement an interface method in the case below? Currently, it shows an error "not all code paths return a value".

This is my home task. The class "Time" is already implemented and works properly. I tried to find any examples of successful implementation of this method on the Internet but failed.

class MyCollection : ICollection<Time> 
    {
        List<Time> arr = new List<Time>();

        int ICollection<Time>.Count
        {

            get
            {
                arr.Count();
            }    
        }
     }

I am getting an error:

CS0161 "MyCollection.ICollection.Count.get': not all code paths return a value"

You are missing a return statement on your getter .

class MyCollection : ICollection<Time> 
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count
    {

        get
        {
            return arr.Count();
        }    
    }
 }

Also, you can use Expression body definition =>

class MyCollection : ICollection<Time>
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count => arr.Count;
}

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