C# -> If ... Throw Warning ... Else if... Throw Error.. Else.. Return -
iv'e looked in few sites , seems have not found answer let's iv'e got struct "mystruct"
public struct mystruct { private int value; private mystruct(int i) { value = i; } public static implicit operator mystruct(int i) { return new mystruct(i); } public static implicit operator int (mystruct ms) { return ms.value; } public static explicit operator uint (mystruct i) { return convert.touint32(i); } }
and want on explicit operator that
if (i< 40) throw compiler warning else if (i > 50) throw compiler error else -> return value
i know can use throw exception, want warning/error part this:
public class program { static void main() { mystruct ms1 = 30; mystruct ms2 = 60; console.writeline((uint)ms1);//so throw warning console.writeline((uint)ms2);//so throw error console.readkey(); } }
if i'm trying that:
public static explicit operator uint (mystruct i) { if (i < 40) { #warning number must less 50 , bigger 40 } else if (i > 50) { #error number must less 50 , bigger 40 } return convert.touint32(i); }
it throws warning , error without calling operator , cant use #if/#else on variables
and if use obsolete attribute, same
any appriciate! :)
even using roslyn extension, not in general able achieve this.
in examples show, in theory possible (in roslyn, gives compile-time hooks), there require non-trivial analysis of code identify values of mystruct
variables @ run-time when explicit uint
operator called.
but other examples not able accomplish this. mystruct
value come anywhere, initialized value. there's no reason initialization should occur int
literal in same method being analyzed, , initialization hidden analyzer (well, analyzer supported current c# compiler).
indeed, 1 of things makes variables powerful can contain arbitrary values, passed around in code, manipulated, etc. same power makes impractical try detect @ compile time value of variable would @ run time.
it's not clear question broader issue you're trying resolve. whatever is, you're going in wrong way. recommend post new question , precisely explains broader issue is, can receive specific on that.
Comments
Post a Comment