-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathConsume.cs
More file actions
1419 lines (1237 loc) · 50.8 KB
/
Consume.cs
File metadata and controls
1419 lines (1237 loc) · 50.8 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ReSharper disable RedundantUsingDirective
// ReSharper disable RedundantAssignment
// ReSharper disable UnusedVariable
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedParameter.Local
// ReSharper disable PossibleMultipleEnumeration
// ReSharper disable AllUnderscoreLocalParameterName
// ReSharper disable NotAccessedVariable
// ReSharper disable UnnecessaryWhitespace
// ReSharper disable InconsistentNaming
// ReSharper disable CollectionNeverUpdated.Local
#nullable enable
namespace Consumes;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
#if FeatureMemory
using System.Buffers.Binary;
#endif
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using MemoryStream = System.IO.MemoryStream;
// ReSharper disable MethodHasAsyncOverload
// ReSharper disable RedundantCast
// ReSharper disable NotAccessedField.Local
#pragma warning disable CS0219 // Variable is assigned but its value is never used
#pragma warning disable CS0414 // Field is assigned but its value is never used
#pragma warning disable CS0169 // Field is never used
#pragma warning disable CS4014
#pragma warning disable CA1416
[SuppressMessage("Performance", "CA1823:Avoid unused private fields")]
class Consume
{
Consume()
{
var type = typeof(AllowNullAttribute);
type = typeof(DisallowNullAttribute);
type = typeof(DoesNotReturnAttribute);
type = typeof(DoesNotReturnIfAttribute);
type = typeof(MaybeNullAttribute);
type = typeof(MaybeNullWhenAttribute);
type = typeof(MemberNotNullAttribute);
type = typeof(MemberNotNullWhenAttribute);
type = typeof(NotNullAttribute);
type = typeof(NotNullIfNotNullAttribute);
type = typeof(NotNullWhenAttribute);
type = typeof(ParamCollectionAttribute);
type = typeof(CallerArgumentExpressionAttribute);
type = typeof(IsExternalInit);
type = typeof(KeyValuePair);
type = typeof(FeatureGuardAttribute);
type = typeof(FeatureSwitchDefinitionAttribute);
type = typeof(ModuleInitializerAttribute);
type = typeof(RequiredMemberAttribute);
type = typeof(SetsRequiredMembersAttribute);
type = typeof(SkipLocalsInitAttribute);
//TODO:
// type = typeof(TupleElementNamesAttribute);
type = typeof(DebuggerNonUserCodeAttribute);
type = typeof(UnscopedRefAttribute);
#if !NoStringInterpolation
type = typeof(InterpolatedStringHandlerArgumentAttribute);
type = typeof(InterpolatedStringHandlerAttribute);
#endif
type = typeof(StringSyntaxAttribute);
#if !NET7_0_OR_GREATER || NET11_0_OR_GREATER
var csharpSyntax = StringSyntaxAttribute.CSharp;
var fsharpSyntax = StringSyntaxAttribute.FSharp;
var vbSyntax = StringSyntaxAttribute.VisualBasic;
#endif
type = typeof(DynamicallyAccessedMembersAttribute);
type = typeof(DynamicDependencyAttribute);
type = typeof(RequiresDynamicCodeAttribute);
type = typeof(RequiresUnreferencedCodeAttribute);
type = typeof(UnconditionalSuppressMessageAttribute);
type = typeof(CompilerFeatureRequiredAttribute);
#if FeatureMemory
type = typeof(CollectionBuilderAttribute);
#endif
//TODO:
//type = typeof(AsyncMethodBuilderAttribute);
#if !NET6_0 && !NET5_0
type = typeof(ObsoletedOSPlatformAttribute);
type = typeof(SupportedOSPlatformGuardAttribute);
type = typeof(UnsupportedOSPlatformGuardAttribute);
#endif
type = typeof(OSPlatformAttribute);
type = typeof(SupportedOSPlatformAttribute);
type = typeof(TargetPlatformAttribute);
type = typeof(UnsupportedOSPlatformAttribute);
type = typeof(StackTraceHiddenAttribute);
type = typeof(UnmanagedCallersOnlyAttribute);
type = typeof(SuppressGCTransitionAttribute);
type = typeof(DisableRuntimeMarshallingAttribute);
type = typeof(RequiresUnreferencedCodeAttribute);
type = typeof(UnreachableException);
type = typeof(DebuggerDisableUserUnhandledExceptionsAttribute);
type = typeof(EnumerationOptions);
type = typeof(MatchType);
type = typeof(MatchCasing);
var (key, value) = KeyValuePair.Create("a", "b");
#if NET6_0_OR_GREATER
var (date, time, offset) = DateTimeOffset.Now;
var (dateOnly, timeOnly) = DateTime.Now;
var (hour, minute) = new TimeOnly();
#endif
var (year, month, day) = DateTime.Now;
#if FeatureValueTask
var completed = ValueTask.CompletedTask;
#endif
}
#if FeatureValueTuple
static (string value1, bool value2) NamedTupleMethod() =>
new("value", false);
#endif
#pragma warning disable ExperimentalMethod
static void ExperimentalMethodUsage() =>
ExperimentalMethod();
[Experimental("ExperimentalMethod")]
static void ExperimentalMethod()
{
}
#pragma warning restore ExperimentalMethod
[RequiresPreviewFeatures("This method uses a preview feature.")]
void UsePreviewFeature()
{
}
public static void ParamCollection(params List<string> collection)
{
}
[OverloadResolutionPriority(1)]
void Method(int x)
{
}
[OverloadResolutionPriority(2)]
void Method(string x)
{
}
[OverloadResolutionPriority(3)]
void Method(object x)
{
}
void GuidUsage()
{
var guid = Guid.CreateVersion7();
guid = Guid.CreateVersion7(timestamp: DateTimeOffset.UtcNow);
var result = Guid.TryParse(s: "", provider: null, result: out guid);
#if FeatureMemory
ReadOnlySpan<byte> byteSpan = default;
result = Guid.TryParse(utf8Text: byteSpan, result: out guid);
guid = Guid.Parse(utf8Text: byteSpan);
Span<char> charSpan = default;
result = Guid.TryParse(input: charSpan, result: out guid);
result = Guid.TryParse(s: charSpan, provider: null, result: out guid);
result = Guid.TryParseExact(input: charSpan, format: charSpan, result: out guid);
#endif
}
void SHA256Usage()
{
SHA256.HashData(source: (byte[]) null!);
SHA256.HashData(source: (Stream) null!);
#if FeatureValueTask
SHA256.HashDataAsync(source: null!, cancellationToken: CancellationToken.None);
#endif
#if FeatureMemory
Span<byte> span = default;
ReadOnlySpan<byte> readOnlySpan = default;
Memory<byte> memory = default;
SHA256.HashData(source: (Stream) null!, destination: span);
SHA256.HashData(source: readOnlySpan);
SHA256.HashData(source: readOnlySpan, destination: span);
SHA256.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _);
#if FeatureValueTask
SHA256.HashDataAsync(source: null!, destination: memory);
SHA256.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None);
#endif
#endif
}
void SHA512Usage()
{
SHA512.HashData(source: (byte[]) null!);
SHA512.HashData(source: (Stream) null!);
#if FeatureValueTask
SHA512.HashDataAsync(source: null!, cancellationToken: CancellationToken.None);
#endif
#if FeatureMemory
Span<byte> span = default;
ReadOnlySpan<byte> readOnlySpan = default;
Memory<byte> memory = default;
SHA512.HashData((Stream) null!, destination: span);
SHA512.HashData(source: readOnlySpan);
SHA512.HashData(source: readOnlySpan, destination: span);
SHA512.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _);
#if FeatureValueTask
SHA512.HashDataAsync(source: null!, destination: memory);
SHA512.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None);
#endif
#endif
}
void SHA1Usage()
{
SHA1.HashData(source: (byte[]) null!);
SHA1.HashData(source: (Stream) null!);
#if FeatureValueTask
SHA1.HashDataAsync(source: null!, cancellationToken: CancellationToken.None);
#endif
#if FeatureMemory
Span<byte> span = default;
ReadOnlySpan<byte> readOnlySpan = default;
Memory<byte> memory = default;
SHA1.HashData(source: (Stream) null!, destination: span);
SHA1.HashData(source: readOnlySpan);
SHA1.HashData(source: readOnlySpan, destination: span);
SHA1.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _);
#if FeatureValueTask
SHA1.HashDataAsync(source: null!, destination: memory);
SHA1.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None);
#endif
#endif
}
void SHA384Usage()
{
SHA384.HashData(source: (byte[]) null!);
SHA384.HashData(source: (Stream) null!);
#if FeatureValueTask
SHA384.HashDataAsync(source: null!, cancellationToken: CancellationToken.None);
#endif
#if FeatureMemory
Span<byte> span = default;
ReadOnlySpan<byte> readOnlySpan = default;
Memory<byte> memory = default;
SHA384.HashData(source: (Stream) null!, destination: span);
SHA384.HashData(source: readOnlySpan);
SHA384.HashData(source: readOnlySpan, destination: span);
SHA384.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _);
#if FeatureValueTask
SHA384.HashDataAsync(source: null!, destination: memory);
SHA384.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None);
#endif
#endif
}
void MD5Usage()
{
MD5.HashData(source: (byte[]) null!);
MD5.HashData(source: (Stream) null!);
#if FeatureValueTask
MD5.HashDataAsync(source: null!, cancellationToken: CancellationToken.None);
#endif
#if FeatureMemory
Span<byte> span = default;
ReadOnlySpan<byte> readOnlySpan = default;
Memory<byte> memory = default;
MD5.HashData(source: (Stream) null!, destination: span);
MD5.HashData(source: readOnlySpan);
MD5.HashData(source: readOnlySpan, destination: span);
MD5.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _);
#if FeatureValueTask
MD5.HashDataAsync(source: null!, destination: memory);
MD5.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None);
#endif
#endif
}
#if FeatureMemory
void CollectionBuilderAttribute()
{
MyCollection myCollection = [1, 2, 3, 4, 5];
}
[CollectionBuilder(typeof(MyCollection), nameof(Create))]
class MyCollection(ReadOnlySpan<int> initValues)
{
int[] values = initValues.ToArray();
public IEnumerator<int> GetEnumerator() => ((IEnumerable<int>) values).GetEnumerator();
public static MyCollection Create(ReadOnlySpan<int> values) => new(values);
}
#endif
#if FeatureValueTuple
void Ranges()
{
var range = "value"[1..];
var index = "value"[^2];
//Array not supported due to no RuntimeHelpers.GetSubArray
// var subArray = new[]
// {
// "value1",
// "value2"
// }[..1];
}
#endif
#if FeatureMemory
void BitConverter_Methods()
{
var floatFromInt = BitConverter.Int32BitsToSingle(0x3F800000);
var intFromFloat = BitConverter.SingleToInt32Bits(1.0f);
var floatFromUInt = BitConverter.UInt32BitsToSingle(0x3F800000u);
var uintFromFloat = BitConverter.SingleToUInt32Bits(1.0f);
var doubleFromULong = BitConverter.UInt64BitsToDouble(0x3FF0000000000000ul);
var ulongFromDouble = BitConverter.DoubleToUInt64Bits(1.0);
}
void BinaryPrimitives_Methods()
{
var buffer = new byte[8];
Span<byte> span = buffer;
ReadOnlySpan<byte> roSpan = buffer;
var d1 = BinaryPrimitives.ReadDoubleBigEndian(roSpan);
var d2 = BinaryPrimitives.ReadDoubleLittleEndian(roSpan);
var f1 = BinaryPrimitives.ReadSingleBigEndian(roSpan);
var f2 = BinaryPrimitives.ReadSingleLittleEndian(roSpan);
BinaryPrimitives.TryReadDoubleBigEndian(roSpan, out _);
BinaryPrimitives.TryReadDoubleLittleEndian(roSpan, out _);
BinaryPrimitives.TryReadSingleBigEndian(roSpan, out _);
BinaryPrimitives.TryReadSingleLittleEndian(roSpan, out _);
BinaryPrimitives.WriteDoubleBigEndian(span, 1.0);
BinaryPrimitives.WriteDoubleLittleEndian(span, 1.0);
BinaryPrimitives.WriteSingleBigEndian(span, 1.0f);
BinaryPrimitives.WriteSingleLittleEndian(span, 1.0f);
BinaryPrimitives.TryWriteDoubleBigEndian(span, 1.0);
BinaryPrimitives.TryWriteDoubleLittleEndian(span, 1.0);
BinaryPrimitives.TryWriteSingleBigEndian(span, 1.0f);
BinaryPrimitives.TryWriteSingleLittleEndian(span, 1.0f);
}
#endif
void Byte_Methods()
{
byte.TryParse(s: "1", provider: null, result: out _);
#if FeatureMemory
byte.TryParse(utf8Text: "1"u8, provider: null, result: out _);
byte.TryParse(s: ['1'], result: out _);
byte.TryParse(s: ['1'], provider: null, result: out _);
byte.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _);
byte.TryParse(utf8Text: "1"u8, result: out _);
byte.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _);
#endif
}
#if FeatureMemory
void Convert_Methods()
{
Convert.TryFromBase64Chars("SGVsbG8=".AsSpan(), stackalloc byte[5], out _);
Convert.TryFromBase64String("SGVsbG8=", stackalloc byte[5], out _);
Convert.TryToBase64Chars("Hello"u8, stackalloc char[8], out _);
Convert.TryToHexString(new byte[] { 0x0F }.AsSpan(), stackalloc char[2], out _);
Convert.TryToHexString(new byte[] { 0x0F }.AsSpan(), stackalloc byte[2], out _);
Convert.TryToHexStringLower(new byte[] { 0x0F }.AsSpan(), stackalloc char[2], out _);
Convert.TryToHexStringLower(new byte[] { 0x0F }.AsSpan(), stackalloc byte[2], out _);
Convert.FromHexString("0F".AsSpan(), stackalloc byte[1], out _, out _);
Convert.FromHexString("0F", stackalloc byte[1], out _, out _);
Convert.FromHexString("0F"u8);
Convert.FromHexString("0F"u8, stackalloc byte[1], out _, out _);
}
#endif
void CancellationToken_Methods()
{
var source = new CancellationTokenSource();
var token = source.Token;
token.UnsafeRegister(_ =>
{
}, null);
token.UnsafeRegister((_, _) =>
{
}, null);
}
async Task CancellationTokenSource_Methods()
{
var source = new CancellationTokenSource();
await source.CancelAsync();
}
void Char_Methods()
{
var isAscii = char.IsAscii('\u0000');
var isAsciiLetterOrDigit = char.IsAsciiLetterOrDigit('\u0061');
var isAsciiLetter = char.IsAsciiLetter('\u007a');
var isAsciiLetterUpper = char.IsAsciiLetterUpper('\u0045');
var isAsciiLetterLower = char.IsAsciiLetterLower('\u0040');
var isAsciiDigit = char.IsAsciiDigit('\u0035');
var isAsciiHexDigit = char.IsAsciiHexDigit('\u0066');
var isAsciiHexDigitLower = char.IsAsciiHexDigitLower('\u0063');
var isAsciiHexDigitUpper = char.IsAsciiHexDigitUpper('\u0041');
var charEquals = 'A'.Equals('a', StringComparison.OrdinalIgnoreCase);
}
class WithMethods
{
public void NonGenericMethod(string value) { }
public void GenericMethod<T>(string value) { }
public void GenericMethod<T1, T2>(string value, int count) { }
}
void Type_GetMethod()
{
var type = typeof(WithMethods);
// Non-generic method
var nonGeneric = type.GetMethod("NonGenericMethod", 0, BindingFlags.Public | BindingFlags.Instance, [typeof(string)]);
// Generic method with 1 type parameter
var generic1 = type.GetMethod("GenericMethod", 1, BindingFlags.Public | BindingFlags.Instance, [typeof(string)]);
// Generic method with 2 type parameters
var generic2 = type.GetMethod("GenericMethod", 2, BindingFlags.Public | BindingFlags.Instance, [typeof(string), typeof(int)]);
}
void ConcurrentDictionary_Methods()
{
var dict = new ConcurrentDictionary<string, int>();
var value = dict.GetOrAdd("Hello", static (_, arg) => arg.Length, "World");
}
#if FeatureMemory
void String_Normalize()
{
var span = "Café".AsSpan();
var normalizedLength = span.GetNormalizedLength(NormalizationForm.FormC);
var isNormalized = span.IsNormalized(NormalizationForm.FormC);
Span<char> destination = new char[10];
var tryNormalize = span.TryNormalize(destination, out var chars, NormalizationForm.FormC);
}
#endif
#if NET9_0_OR_GREATER
void OrderedDictionary_Methods()
{
var dict = new OrderedDictionary<string, int>();
var result = dict.TryAdd("Hello", 1, out var index1);
result = dict.TryGetValue("Hello", out var value, out var index2);
}
#endif
void ConcurrentBag_Methods()
{
var bag = new ConcurrentBag<string>();
bag.Clear();
}
void ConcurrentQueue_Methods()
{
var queue = new ConcurrentQueue<string>();
queue.Clear();
}
void Dictionary_Methods()
{
var dictionary = new Dictionary<string, string?> {{"key", "value"}};
dictionary.GetValueOrDefault("key");
dictionary.GetValueOrDefault("key", "default");
dictionary.TryAdd("key", "value");
dictionary.Remove("key");
dictionary.EnsureCapacity(1);
dictionary.TrimExcess(1);
dictionary.TrimExcess();
IDictionary<string, string?> iDictionary = dictionary;
iDictionary.TryAdd("key", "value");
iDictionary.TryAdd("key", "value");
iDictionary.Remove("key");
IEnumerable<KeyValuePair<string, string?>> pairs = dictionary;
pairs.ToDictionary();
pairs.ToDictionary(StringComparer.Ordinal);
}
void Lock_Methods()
{
var locker = new Lock();
var held = locker.IsHeldByCurrentThread;
locker.Enter();
}
#if PolyArgumentExceptions
#region ArgumentExceptionUsage
void ArgumentExceptionExample(Order order, Customer customer, string customerId, string email, decimal discountPercentage, int quantity)
{
ArgumentNullException.ThrowIfNull(order);
ArgumentNullException.ThrowIfNull(customer);
ArgumentException.ThrowIfNullOrWhiteSpace(customerId);
ArgumentException.ThrowIfNullOrWhiteSpace(email);
ArgumentOutOfRangeException.ThrowIfGreaterThan(discountPercentage, 100m);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
this.order = order;
this.customer = customer;
this.customerId = customerId;
this.email = email;
this.discountPercentage = discountPercentage;
this.quantity = quantity;
}
void ObjectDisposedExceptionExample(bool isDisposed)
{
ObjectDisposedException.ThrowIf(isDisposed, this);
ObjectDisposedException.ThrowIf(isDisposed, typeof(Consume));
}
#endregion
#endif
#if PolyEnsure
#region EnsureUsage
void EnsureExample(Order order, Customer customer, string customerId, string email, decimal discountPercentage, int quantity)
{
this.order = Ensure.NotNull(order);
this.customer = Ensure.NotNull(customer);
this.customerId = Ensure.NotNullOrWhiteSpace(customerId);
this.email = Ensure.NotNullOrWhiteSpace(email);
this.discountPercentage = Ensure.NotGreaterThan(discountPercentage, 100m);
this.quantity = Ensure.NotNegativeOrZero(quantity);
}
#endregion
#endif
decimal discountPercentage;
int quantity;
string email = null!;
string customerId = null!;
Customer customer = null!;
Order order = null!;
class Customer;
class Order;
void Double_Methods()
{
double.TryParse(s: "1", provider: null, result: out _);
#if FeatureMemory
double.TryParse(utf8Text: "1"u8, provider: null, result: out _);
double.TryParse(s: ['1'], result: out _);
double.TryParse(s: ['1'], provider: null, result: out _);
double.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _);
double.TryParse(utf8Text: "1"u8, result: out _);
double.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _);
#endif
}
void DictionaryEntry_Methods()
{
var entry = new DictionaryEntry("key", "value");
var (key, value) = entry;
}
void ExceptionDispatchInfo_Methods()
{
var ex = new Exception("test");
ExceptionDispatchInfo.SetCurrentStackTrace(ex);
}
void Enum_Methods()
{
var values = Enum.GetValuesAsUnderlyingType(typeof(DayOfWeek));
values = Enum.GetValuesAsUnderlyingType<DayOfWeek>();
}
void Encoding_Methods()
{
var latin1 = Encoding.Latin1;
}
void Environment_Methods()
{
var processPath = Environment.ProcessPath;
}
void EnumerationOptions_Methods()
{
var options = new EnumerationOptions
{
RecurseSubdirectories = true,
BufferSize = 4096,
AttributesToSkip = FileAttributes.ReadOnly,
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive,
ReturnSpecialDirectories = true
};
var recurse = options.RecurseSubdirectories;
var buffer = options.BufferSize;
var attrs = options.AttributesToSkip;
var matchType = options.MatchType;
var matchCasing = options.MatchCasing;
var special = options.ReturnSpecialDirectories;
}
#if NETFRAMEWORK || NETSTANDARD && !NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_0
void Directory_Methods_WithEnumerationOptions()
{
var options = new EnumerationOptions();
var files = Polyfill.EnumerateFiles(".", "*", options);
var dirs = Polyfill.EnumerateDirectories(".", "*", options);
var entries = Polyfill.EnumerateFileSystemEntries(".", "*", options);
var filesArray = Polyfill.GetFiles(".", "*", options);
var dirsArray = Polyfill.GetDirectories(".", "*", options);
var entriesArray = Polyfill.GetFileSystemEntries(".", "*", options);
}
void DirectoryInfo_Methods_WithEnumerationOptions()
{
var dirInfo = new DirectoryInfo(".");
var options = new EnumerationOptions();
var files = dirInfo.EnumerateFiles("*", options);
var dirs = dirInfo.EnumerateDirectories("*", options);
var entries = dirInfo.EnumerateFileSystemInfos("*", options);
var filesArray = dirInfo.GetFiles("*", options);
var dirsArray = dirInfo.GetDirectories("*", options);
var entriesArray = dirInfo.GetFileSystemInfos("*", options);
}
#else
void Directory_Methods_WithEnumerationOptions()
{
var options = new EnumerationOptions();
var files = Directory.EnumerateFiles(".", "*", options);
var dirs = Directory.EnumerateDirectories(".", "*", options);
var entries = Directory.EnumerateFileSystemEntries(".", "*", options);
var filesArray = Directory.GetFiles(".", "*", options);
var dirsArray = Directory.GetDirectories(".", "*", options);
var entriesArray = Directory.GetFileSystemEntries(".", "*", options);
}
void DirectoryInfo_Methods_WithEnumerationOptions()
{
var dirInfo = new DirectoryInfo(".");
var options = new EnumerationOptions();
var files = dirInfo.EnumerateFiles("*", options);
var dirs = dirInfo.EnumerateDirectories("*", options);
var entries = dirInfo.EnumerateFileSystemInfos("*", options);
var filesArray = dirInfo.GetFiles("*", options);
var dirsArray = dirInfo.GetDirectories("*", options);
var entriesArray = dirInfo.GetFileSystemInfos("*", options);
}
#endif
void Path_Methods()
{
var relative = Path.GetRelativePath("/folder1/folder2", "/folder1/folder3");
}
void Console_Methods()
{
using var stdin = Console.OpenStandardInputHandle();
using var stdout = Console.OpenStandardOutputHandle();
using var stderr = Console.OpenStandardErrorHandle();
}
void File_Methods()
{
const string TestFilePath = "testfile.txt";
var sourceContent = "Test content";
File.WriteAllText(TestFilePath, sourceContent);
var fileMode = File.GetUnixFileMode(TestFilePath);
// Use the | bitwise OR operator to combine multiple file modes
File.SetUnixFileMode(TestFilePath, UnixFileMode.OtherRead | UnixFileMode.OtherWrite);
#if !NET11_0_OR_GREATER
using var nullHandle = File.OpenNullHandle();
#endif
var hardLink = File.CreateHardLink("hardlink.txt", TestFilePath);
var fileInfo = new FileInfo("hardlink2.txt");
fileInfo.CreateAsHardLink(TestFilePath);
}
void HashSet_Methods()
{
var set = new HashSet<string> {"value"};
var found = set.TryGetValue("value", out var result);
set.EnsureCapacity(1);
set.TrimExcess(1);
set.TrimExcess();
}
#if FeatureHttp
void HttpClient_Methods(HttpClient target)
{
target.PatchAsync("", new StringContent(""));
target.PatchAsync(new Uri("http://a"), new StringContent(""));
target.PatchAsync("", new StringContent(""), CancellationToken.None);
target.PatchAsync(new Uri("http://a"), new StringContent(""), CancellationToken.None);
target.Send(new HttpRequestMessage());
target.Send(new HttpRequestMessage(), HttpCompletionOption.ResponseContentRead);
target.Send(new HttpRequestMessage(), CancellationToken.None);
target.Send(new HttpRequestMessage(), HttpCompletionOption.ResponseContentRead, CancellationToken.None);
target.GetStreamAsync("", CancellationToken.None);
target.GetStreamAsync(new Uri(""), CancellationToken.None);
target.GetByteArrayAsync("", CancellationToken.None);
target.GetByteArrayAsync(new Uri(""), CancellationToken.None);
target.GetStringAsync("", CancellationToken.None);
target.GetStringAsync(new Uri(""), CancellationToken.None);
}
void HttpContent_Methods(ByteArrayContent target)
{
target.ReadAsStream();
target.ReadAsStream(CancellationToken.None);
target.CopyTo(System.IO.Stream.Null, null, CancellationToken.None);
target.CopyToAsync(System.IO.Stream.Null, CancellationToken.None);
target.CopyToAsync(System.IO.Stream.Null, null, CancellationToken.None);
target.ReadAsStreamAsync(CancellationToken.None);
target.ReadAsByteArrayAsync(CancellationToken.None);
target.ReadAsStringAsync(CancellationToken.None);
target.LoadIntoBufferAsync(CancellationToken.None);
target.LoadIntoBufferAsync(1024, CancellationToken.None);
}
#endif
#if FeatureValueTask
async Task TcpClient_Methods()
{
using var client = new TcpClient();
await client.ConnectAsync(IPAddress.Loopback, 12345, CancellationToken.None);
await client.ConnectAsync([IPAddress.Loopback], 12345, CancellationToken.None);
await client.ConnectAsync("localhost", 12345, CancellationToken.None);
await client.ConnectAsync(new(IPAddress.Loopback, 12345), CancellationToken.None);
}
async Task UdpClient_Methods()
{
using var client = new UdpClient(0);
await client.ReceiveAsync(CancellationToken.None);
#if FeatureMemory
var data = new ReadOnlyMemory<byte>([1, 2, 3]);
using var connectedClient = new UdpClient("localhost", 12345);
await connectedClient.SendAsync(data, CancellationToken.None);
await client.SendAsync(data, new(IPAddress.Loopback, 12345), CancellationToken.None);
await client.SendAsync(data, "localhost", 12345, CancellationToken.None);
#endif
}
#endif
void IDictionary_Methods()
{
IDictionary<int, int> idictionary = new Dictionary<int, int>();
idictionary.AsReadOnly();
}
void IEnumerable_Methods()
{
IEnumerable<string> enumerable = new List<string>
{
"a",
"b"
};
enumerable.TryGetNonEnumeratedCount(out var count);
var append = enumerable.Append("c");
var maxBy = enumerable.MaxBy(_ => _);
var chunk = enumerable.Chunk(3);
var minBy = enumerable.MinBy(_ => _);
var distinctBy = enumerable.DistinctBy(_ => _);
var skipLast = enumerable.SkipLast(1);
int[] numbers = [1, 2, 3, 4];
string[] words = ["one", "two", "three"];
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
#if FeatureValueTuple
var elementAt = enumerable.ElementAt(new Index(1));
var take = enumerable.Take(1..3);
#endif
var takeLast = enumerable.TakeLast(3);
var unionBy = enumerable.UnionBy(["c"], _ => _, comparer: default);
var reverse = new[] {"a", "b"}.Reverse();
var order = enumerable.Order();
var orderComparer = enumerable.Order(StringComparer.Ordinal);
var orderDescending = enumerable.OrderDescending();
var orderDescendingComparer = enumerable.OrderDescending(StringComparer.Ordinal);
IEnumerable<int> lengths = [1];
var intersectBy = enumerable.IntersectBy(lengths, _ => _.Length);
var intersectByComparer = enumerable.IntersectBy(lengths, _ => _.Length, EqualityComparer<int>.Default);
#if FeatureValueTuple
IEnumerable<(string Key, int Value)> inner = [("a", 1)];
var leftJoin = enumerable.LeftJoin(inner, _ => _, _ => _.Key, (o, i) => $"{o}-{i.Value}");
var leftJoinComparer = enumerable.LeftJoin(inner, _ => _, _ => _.Key, (o, i) => $"{o}-{i.Value}", StringComparer.OrdinalIgnoreCase);
var rightJoin = enumerable.RightJoin(inner, _ => _, _ => _.Key, (o, i) => $"{o}-{i.Value}");
var rightJoinComparer = enumerable.RightJoin(inner, _ => _, _ => _.Key, (o, i) => $"{o}-{i.Value}", StringComparer.OrdinalIgnoreCase);
#endif
}
void IList_Methods()
{
IList<string> ilist = new List<string>();
ilist.AsReadOnly();
}
#if FeatureMemory && FeatureUnsafe
void Interlocked_Methods()
{
var intValue = 0xFF;
Interlocked.And(ref intValue, 0x0F);
Interlocked.Or(ref intValue, 0xF0);
var longValue = 0xFFL;
Interlocked.And(ref longValue, 0x0FL);
Interlocked.Or(ref longValue, 0xF0L);
}
#endif
void Int_Methods()
{
int.TryParse(s: "1", provider: null, result: out _);
#if FeatureMemory
int.TryParse(utf8Text: "1"u8, provider: null, result: out _);
int.TryParse(s: ['1'], result: out _);
int.TryParse(s: ['1'], provider: null, result: out _);
int.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _);
int.TryParse(utf8Text: "1"u8, result: out _);
int.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _);
#endif
}
void List_Methods()
{
var list = new List<char>();
list.EnsureCapacity(1);
list.TrimExcess();
#if FeatureMemory
var array = new char[1];
list.AddRange("ab".AsSpan());
list.CopyTo(array.AsSpan());
list.InsertRange(1, "bc".AsSpan());
#endif
}
void Queue_Methods()
{
var queue = new Queue<char>();
queue.EnsureCapacity(1);
queue.TrimExcess(1);
queue.TrimExcess();
}
#if NET6_0_OR_GREATER
void PriorityQueue_Methods()
{
var pq = new PriorityQueue<string, int>();
pq.Remove("item", out _, out _);
pq.Remove("item", out _, out _, StringComparer.Ordinal);
}
#endif
void Long_Methods()
{
long.TryParse(s: "1", provider: null, result: out _);
#if FeatureMemory
long.TryParse(utf8Text: "1"u8, provider: null, result: out _);
long.TryParse(s: ['1'], result: out _);
long.TryParse(s: ['1'], provider: null, result: out _);
long.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _);
long.TryParse(utf8Text: "1"u8, result: out _);
long.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _);
#endif
}
void MemberInfo_Methods(MemberInfo info)
{
var result = info.HasSameMetadataDefinitionAs(info);
}
#if FeatureRuntimeInformation
void OperatingSystem_Methods()
{
var isOSPlatform = OperatingSystem.IsOSPlatform("windows");
var isOSPlatformWindows10 = OperatingSystem.IsOSPlatformVersionAtLeast("windows", 10, 0, 10240);
var isWindows = OperatingSystem.IsWindows();
var isWindows11 = OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000);
var isMacOS = OperatingSystem.IsMacOS();
var isMacOsSonoma = OperatingSystem.IsMacOSVersionAtLeast(14);
var isMacCatalyst = OperatingSystem.IsMacCatalyst();
var isMacCatalyst17 = OperatingSystem.IsMacCatalystVersionAtLeast(17);
var isLinux = OperatingSystem.IsLinux();
var isFreeBSD = OperatingSystem.IsFreeBSD();
var isFreeBSD14 = OperatingSystem.IsFreeBSDVersionAtLeast(14, 0);
var isIOS = OperatingSystem.IsIOS();
var isIOS18 = OperatingSystem.IsIOSVersionAtLeast(18);
var isAndroid = OperatingSystem.IsAndroid();
var isAndroid13 = OperatingSystem.IsAndroidVersionAtLeast(13);
var isTvOS = OperatingSystem.IsTvOS();
var isTvOS17 = OperatingSystem.IsTvOSVersionAtLeast(17);
var isWatchOS = OperatingSystem.IsWatchOS();
var isWatchOS11 = OperatingSystem.IsWatchOSVersionAtLeast(11);
var isWasi = OperatingSystem.IsWasi();
var isBrowser = OperatingSystem.IsBrowser();
}
#endif
async Task Process_Methods()
{
var process = new Process();
await process.WaitForExitAsync();
process.Kill(true);
}
void ProcessStartInfo_Methods()
{
var info = new ProcessStartInfo("cmd.exe");
var argumentList = info.ArgumentList;
argumentList.Add("/c");
}
void Random_Methods()
{
var random = new Random();
#if FeatureMemory
Span<byte> bufferSpan = new byte[10];
random.NextBytes(bufferSpan);
random.Shuffle(bufferSpan);
ReadOnlySpan<int> choicesSpan = [1, 2, 3, 4, 5];
Span<int> destination = new int[10];
random.GetItems(choicesSpan, destination);
var resultFromSpan = random.GetItems(choicesSpan, 10);
#endif
int[] choicesArray = [1, 2, 3, 4, 5];
var resultFromArray = random.GetItems(choicesArray, 10);