0

Forgive me if my question is technically worded wrong but I basically need an anonymous method or a Func delegate to encapsulate the following functionality:

                if (Cache.CurrentCustomer == null)
                {
                    return null;
                }
                else
                {
                    return Cache.CurrentCustomer.PersonID; // (Guid type)
                }

The above if statement will return a value that is going to be assigned against an Order entity that has a PersonID property field exposed that accepts a nullable guid type.

If a Func delegate is possible then can instantiate on the fly like:

orderToInsert.PersonID = new Func() => { ... }

I would typically ship my if statement scenario out into a help support method this is a good opportunity to learn something I have been trying to pick for ages! TIA!!!

IbrarMumtaz
  • 4,235
  • 7
  • 44
  • 63

1 Answers1

4

Here it is in lambda form:

Func<Guid?> lambda = () => Cache.CurrentCustomer == null 
                             ? (Guid?)null 
                             : Cache.CurrentCustomer.PersonID;

You would then use it as in

orderToInsert.PersonID = lambda();

Update: If you are only trying to see what's possible here, then you can also do this:

orderToInsert.PersonID = (() => Cache.CurrentCustomer == null 
                             ? (Guid?)null 
                             : Cache.CurrentCustomer.PersonID)();

which is really just a roundabout way of doing the classic:

orderToInsert.PersonID = Cache.CurrentCustomer == null 
                             ? (Guid?)null 
                             : Cache.CurrentCustomer.PersonID;
Jon
  • 428,835
  • 81
  • 738
  • 806
  • TY for the swift response, but can I use it as described in the second half of my question??? ----------- Basically I just want to learn that's all I would normally just use a plan method. I think I know how to use it inline, let me try this out. – IbrarMumtaz Sep 12 '11 at 14:22
  • @IbrarMumtaz: I don't understand what you are trying to do here. What exactly do you want to do differently than what we have here? – Jon Sep 12 '11 at 14:28
  • Basically I want to use the expression that your wrote but declare and use it inline. I think its a useful technique to learn now and maybe use it on other areas of my project. – IbrarMumtaz Sep 12 '11 at 14:31
  • Much appreciated I ended up using the classic version. – IbrarMumtaz Sep 12 '11 at 18:08