-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathEmptyManager.cs
100 lines (94 loc) · 2.2 KB
/
EmptyManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
namespace IllidanS4.SharpUtils
{
/// <summary>
/// A class that creates empty instances of types.
/// </summary>
public static class EmptyManager
{
/// <summary>
/// Creates an empty value for a type.
/// </summary>
/// <param name="t">The type.</param>
/// <returns>The empty value.</returns>
public static object GetEmpty(Type t)
{
if(t.IsArray)
{
return Array.CreateInstance(t.GetElementType(), 0);
}else if(t == TypeOf<Missing>.TypeID)
{
return Missing.Value;
}else if(t == TypeOf<EventArgs>.TypeID)
{
return EventArgs.Empty;
}else if(t == TypeOf<Version>.TypeID)
{
return new Version();
}else if(t == TypeOf<string>.TypeID)
{
return String.Empty;
}else if(t == TypeOf<IEnumerable>.TypeID)
{
return new EmptyEnumerable();
}else if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type arg = t.GetGenericArguments()[0];
return Activator.CreateInstance(typeof(EmptyEnumerable<>).MakeGenericType(arg));
}else if(t == TypeOf<Type>.TypeID)
{
return typeof(void);
}else if(t == TypeOf<Enum>.TypeID)
{
return (EmptyEnum)0;
}else if(t == TypeOf<ValueType>.TypeID)
{
return default(EmptyStruct);
}else if(t == TypeOf<Stream>.TypeID)
{
return Stream.Null;
}else if(t == TypeOf<TextWriter>.TypeID)
{
return TextWriter.Null;
}else if(t == TypeOf<TextReader>.TypeID)
{
return TextReader.Null;
}else if(t == TypeOf<DBNull>.TypeID)
{
return DBNull.Value;
}else if(t == TypeOf<Action>.TypeID)
{
return (Action)(()=>{});
}else if(t == TypeOf<IPAddress>.TypeID)
{
return IPAddress.None;
}
return null;
}
private class EmptyEnumerable : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield break;
}
}
private class EmptyEnumerable<T> : IEnumerable<T>
{
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
yield break;
}
}
private enum EmptyEnum{}
private struct EmptyStruct{}
}
}