Friday, 15 July 2011

c# - Defining and using a Global Generic List in WCF Application -



c# - Defining and using a Global Generic List in WCF Application -

i sending few separate messages asp.net site wcf server.

these messages coming through individually, , need server pick them up, , 'stitch' them together.

what trying set methods in global list, using list in different class bidding.

so far have...

variables.cs

class variables { public static list<string> messagestitches { get; set; } }

program.cs

if (!string.isnullorempty(node)) { variables.messagestitches.add(node); }

but getting error:

object reference not set instance of object.

can see going wrong, , how prepare it?

you have not set variables.messagestitches property new list.

you have several options, best alternative 1 or 2.

1 - assign new list in constructor of variables. however, list static, not help you, may not have instantiated variables class, , constructor not have run. can have static constructor though:

class variables { public static list<string> messagestitches { get; set; } // static constructor static variables() { messagestitches = new list<string>(); } }

2 - don't utilize auto-properties. instead, have backing field property, assigned value @ initialisation:

public class variables { private static list<string> messagestitches = new list<string>(); public static list<string> messagestitches { { homecoming messagestitches; } set { messagestitches = value; } }

3 - check list before using ensure it's not null and, if is, assign new list then. again, not threadsafe, unless take steps create (e.g. entering critical section)

if (!string.isnullorempty(node)) { if (variables.messagestitches == null) { variables.messagestitches = new list<string>(); } variables.messagestitches.add(node); }

c# asp.net wcf

No comments:

Post a Comment