Skip to content

Commit f77b54f

Browse files
authored
Merge pull request #12 from AntonioFalcao/main
Adding constraint on caching singletons sample code
2 parents cd090a0 + e4b79ad commit f77b54f

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

1.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,13 +192,15 @@ If you need to cache an instance of something based on type, then you can store
192192
public class Factory
193193
{
194194
public T Create<T>()
195+
where T : new()
195196
{
196197
return Cache<T>.Instance;
197198
}
198199

199200
private static class Cache<T>
201+
where T : new()
200202
{
201-
public static readonly T Instance = new T();
203+
public static readonly T Instance = new();
202204
}
203205
}
204206
```
@@ -209,11 +211,13 @@ You can use the JIT to cache instances on your behalf instead of a slower `Concu
209211
public class Factory
210212
{
211213
public T Create<T>()
214+
where T : new()
212215
{
213216
return Cache<T>.Instance;
214217
}
215218

216219
private static class Cache<T>
220+
where T : new()
217221
{
218222
public static readonly T Instance = CallExpensiveMethodToBuildANewInstance();
219223

0 commit comments

Comments
 (0)