开发者

When overriding a method from a parent class; what does NotImplementedException() mean?

Here's an example:

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

namespace SharpLibrary_MediaManager
{
    public class Picture:BaseFile
    {
        public override void GetFileInformation()
 开发者_运维知识库       {
            throw new NotImplementedException();
        }

        public override void GetThumbnail()
        {
            throw new NotImplementedException();
        }
    }
}

Why are those auto-generated for me and what purpose do they serve? I'm very curious. :)


It's what the IDE puts in so that the auto-generated code will compile. It can not put in an empty method because there might need to be a return value. By putting in the exception the reachability analyzer will deduce that all paths through the method either return a value or throw and therefore it will not complain. It also serves the purpose of reminding you at runtime (when you try to execute said method) that you need to write the body for the method.

You should always replace the throw new NotImplementedException(); with logic of your own.

I also find NotImplementedExceptions very useful when doing TDD. I write some tests and then I need to add some code to my class under test so that my tests actually compile. I'll just write the method definition and add a body with throw new NotImplementedException(); (of course I have a code snippet defined for this). Then my tests will compile and fail (red). Then I'll actually write the bodies until my tests pass (green). Then, for relaxing times make it refactor time.


It is stub code. You need to change it do actually do the work but it will still compile before you do. The code will only throw an error if you call that method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜