Can I detect whether I've been given a new object as a parameter?

前端 未结 9 655
日久生厌
日久生厌 2021-01-18 01:31

Short Version

For those who don\'t have the time to read my reasoning for this question below:

Is there any way to enforce a policy of "new obje

9条回答
  •  独厮守ぢ
    2021-01-18 02:14

    Yes, there is a way to do this.

    Sort of.

    If you make your parameter a ref parameter, you'll have to have an existing variable as your argument. You can't do something like this:

    DoSomething(ref new Customer());
    

    If you do, you'll get the error "A ref or out argument must be an assignable variable."

    Of course, using ref has other implications. However, if you're the one writing the method, you don't need to worry about them. As long as you don't reassign the ref parameter inside the method, it won't make any difference whether you use ref or not.

    I'm not saying it's good style, necessarily. You shouldn't use ref or out unless you really, really need to and have no other way to do what you're doing. But using ref will make what you want to do work.

提交回复
热议问题