开发者

Is returning a type pointer the same as 'newing a type'? in c#

Instead of...

Video v = new Video();

I want to do

Video v = GetVideo();

public Video GetVideo()
{
   return new Video();
}

Are these two ca开发者_如何学编程lls totally equal?


They're the same in this case because the method also creates a new Video. However, consider this instead:

private Video video;

public Video GetVideo()
{
   if (video == null)
   {
       video = new Video();
   }
   return video;
}

Now a new Video object will be created only the first call - subsequent calls will return a reference to the existing object.

(That's only a simple example, of course - it could sometimes create a new one, sometimes not, sometimes return null etc.)


Yes, they are. I have used this approach several times to return me an object prepopulated by some default testing values.


Is returning a type pointer the same as 'newing a type'?

It depends on the method returning the object reference.

Your given snippets, for example, are functionally equivalent because GetVideo() does nothing except return a new Video().


At least you can treat them as equal, they will probably be inlined to the same IL code if they reside in the same assembly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜