c# - How to Format Nullable object? -


this case run , wondering if had better more concise way of doing this.

say have variable 'x' of type nullable. example: string, int?, or datetime?

i want x need format x string cannot call .tostring() or other method on x because x might null.

yes, can like

if(x == null) {  console.writeline("empty"); } else {  console.writeline(x.tostring("g")); } 

or

console.writeline("{0}", x == null? "empty" : x.tostring("g")); 

but looking shorter. maybe nothing exists, thought ask , start conversation.

one reason i'm interested in because have large number of variables i'm moving data 1 class or similar , need apply formatting.

so instead of x, i've got a, b, c, ... z , have check each null , apply formatting each , of varios types , require different formatting. shorter , easier copy , paste minimal changes each line nice.

so have clever tricks use this?

i considered ?? operator can't seem find way apply it. on first glance, seems designed situation doesn't @ all.

its useful long don't need apply formatting.

generic helper:

public static class nullablehelper {     public static string tostring<t>(this t? x, string format) t: struct      {         return x.hasvalue ? string.format(format, x.value) : null;     } } 

usage:

int? = 1; i.tostring("{0:000}"); 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -