Skip to content

Commit 7508080

Browse files
authored
Update coding-style to include target-typed new() guideline (#67061)
* Update coding-style to include target-typed new guideline Similar to `var` usage, `new()` usage is only allowed when the Type can be understood from the same line. Fix #53369 * Fix coding style violations
1 parent 0e1c91b commit 7508080

File tree

28 files changed

+93
-89
lines changed

28 files changed

+93
-89
lines changed

docs/coding-guidelines/coding-style.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ The general rule we follow is "use Visual Studio defaults".
2424
9. If a file happens to differ in style from these guidelines (e.g. private members are named `m_member`
2525
rather than `_member`), the existing style in that file takes precedence.
2626
10. We only use `var` when the type is explicitly named on the right-hand side, typically due to either `new` or an explicit cast, e.g. `var stream = new FileStream(...)` not `var stream = OpenStandardInput()`.
27+
- Similarly, target-typed `new()` can only be used when the type is explicitly named on the left-hand side, in a variable definition statement or a field definition statement. e.g. `FileStream stream = new(...);`, but not `stream = new(...);` (where the type was specified on a previous line).
2728
11. We use language keywords instead of BCL types (e.g. `int, string, float` instead of `Int32, String, Single`, etc) for both type references as well as method calls (e.g. `int.Parse` instead of `Int32.Parse`). See issue [#13976](https://github.com/dotnet/runtime/issues/13976) for examples.
2829
12. We use PascalCasing to name all our constant local variables and fields. The only exception is for interop code where the constant value should exactly match the name and value of the code you are calling via interop.
2930
13. We use PascalCasing for all method names, including local functions.

src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor!!, ILoggerFactor
4646
_options = optionsAccessor.Value;
4747
_logger = loggerFactory.CreateLogger<MemoryCache>();
4848

49-
_coherentState = new();
49+
_coherentState = new CoherentState();
5050

5151
if (_options.Clock == null)
5252
{

src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/LegacyPropagator.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ internal static bool TryExtractBaggage(string baggageString, out IEnumerable<Key
165165

166166
if (keyStart < keyEnd && valueStart < currentIndex)
167167
{
168-
baggageList ??= new();
168+
baggageList ??= new List<KeyValuePair<string, string?>>();
169169

170170
// Insert in reverse order for asp.net compatability.
171171
baggageList.Insert(0, new KeyValuePair<string, string?>(

src/libraries/System.Drawing.Common/tests/System/Drawing/ImageAnimator.ManualTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ public void AnimateAndCaptureFrames()
7070
animation.Save(Path.Combine(testOutputFolder, $"{++frameIndexes[imageName]}_{timestamp}.jpg"), ImageFormat.Jpeg);
7171
}));
7272

73-
bitmaps[imageName] = new(Helpers.GetTestBitmapPath(imageName));
73+
bitmaps[imageName] = new Bitmap(Helpers.GetTestBitmapPath(imageName));
7474
ImageAnimator.Animate(bitmaps[imageName], handlers[imageName]);
7575
}
7676

src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ internal string SubTypeComponent
139139
/// This will return an enumerator over a dictionary of the parameter/value pairs.
140140
/// </summary>
141141
internal Dictionary<string, string>.Enumerator ParameterValuePairs =>
142-
(_parameterDictionary ??= new()).GetEnumerator();
142+
(_parameterDictionary ??= new Dictionary<string, string>()).GetEnumerator();
143143
#endregion Internal Properties
144144

145145
#region Internal Methods
@@ -330,7 +330,7 @@ private void ParseParameterAndValue(ReadOnlySpan<char> parameterAndValue)
330330
//Get length of the parameter value
331331
int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex);
332332

333-
(_parameterDictionary ??= new()).Add(
333+
(_parameterDictionary ??= new Dictionary<string, string>()).Add(
334334
ValidateToken(parameterAndValue.Slice(0, equalSignIndex).ToString()),
335335
ValidateQuotedStringOrToken(parameterAndValue.Slice(parameterStartIndex, parameterValueLength).ToString()));
336336

src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/MsQuicNativeMethods.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -841,7 +841,7 @@ internal void SetCallbackHandler(SafeHandle handle, Delegate del, IntPtr context
841841
//
842842
handle.DangerousAddRef(ref handle__addRefd);
843843
IntPtr __handle_gen_native = handle.DangerousGetHandle();
844-
__del_gen_native__marshaller = new(del);
844+
__del_gen_native__marshaller = new AnyDelegateMarshaller(del);
845845
IntPtr __del_gen_native = __del_gen_native__marshaller.Value;
846846
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, void>)_functionPointer)(__handle_gen_native, __del_gen_native, context);
847847
}
@@ -929,7 +929,7 @@ internal uint RegistrationOpen(ref RegistrationConfig config, out SafeMsQuicRegi
929929
//
930930
// Marshal
931931
//
932-
__config_gen_native = new(config);
932+
__config_gen_native = new RegistrationConfig.Native(config);
933933
__retVal = ((delegate* unmanaged[Cdecl]<RegistrationConfig.Native*, IntPtr*, uint>)_functionPointer)(&__config_gen_native, &__registrationContext_gen_native);
934934
__invokeSucceeded = true;
935935
//
@@ -1017,7 +1017,7 @@ internal uint ConfigurationLoadCredential(SafeMsQuicConfigurationHandle configur
10171017
//
10181018
configuration.DangerousAddRef(ref configuration__addRefd);
10191019
IntPtr __configuration_gen_native = configuration.DangerousGetHandle();
1020-
__credConfig_gen_native = new(credConfig);
1020+
__credConfig_gen_native = new CredentialConfig.Native(credConfig);
10211021
__retVal = ((delegate* unmanaged[Cdecl]<IntPtr, CredentialConfig.Native*, uint>)_functionPointer)(__configuration_gen_native, &__credConfig_gen_native);
10221022
//
10231023
// Unmarshal

src/libraries/System.Net.WebSockets/tests/WebSocketDeflateTests.cs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public async Task ReceiveHelloWithContextTakeover()
4444
stream.Enqueue(0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00);
4545
using WebSocket websocket = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
4646
{
47-
DangerousDeflateOptions = new()
47+
DangerousDeflateOptions = new WebSocketDeflateOptions()
4848
});
4949

5050
Memory<byte> buffer = new byte[5];
@@ -74,7 +74,7 @@ public async Task SendHelloWithContextTakeover()
7474
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
7575
{
7676
IsServer = true,
77-
DangerousDeflateOptions = new()
77+
DangerousDeflateOptions = new WebSocketDeflateOptions()
7878
});
7979

8080
await websocket.SendAsync(Encoding.UTF8.GetBytes("Hello"), WebSocketMessageType.Text, true, CancellationToken);
@@ -95,7 +95,7 @@ public async Task SendHelloWithDisableCompression()
9595
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
9696
{
9797
IsServer = true,
98-
DangerousDeflateOptions = new()
98+
DangerousDeflateOptions = new WebSocketDeflateOptions()
9999
});
100100

101101
byte[] bytes = Encoding.UTF8.GetBytes("Hello");
@@ -113,7 +113,7 @@ public async Task SendHelloWithEmptyFrame()
113113
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
114114
{
115115
IsServer = true,
116-
DangerousDeflateOptions = new()
116+
DangerousDeflateOptions = new WebSocketDeflateOptions()
117117
});
118118

119119
byte[] bytes = Encoding.UTF8.GetBytes("Hello");
@@ -123,7 +123,7 @@ public async Task SendHelloWithEmptyFrame()
123123
using WebSocket client = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
124124
{
125125
IsServer = false,
126-
DangerousDeflateOptions = new()
126+
DangerousDeflateOptions = new WebSocketDeflateOptions()
127127
});
128128

129129
ValueWebSocketReceiveResult result = await client.ReceiveAsync(bytes.AsMemory(), CancellationToken);
@@ -141,7 +141,7 @@ public async Task ReceiveHelloWithoutContextTakeover()
141141
WebSocketTestStream stream = new();
142142
using WebSocket websocket = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
143143
{
144-
DangerousDeflateOptions = new()
144+
DangerousDeflateOptions = new WebSocketDeflateOptions()
145145
{
146146
ClientContextTakeover = false
147147
}
@@ -171,7 +171,7 @@ public async Task SendHelloWithoutContextTakeover()
171171
using WebSocket websocket = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
172172
{
173173
IsServer = true,
174-
DangerousDeflateOptions = new()
174+
DangerousDeflateOptions = new WebSocketDeflateOptions()
175175
{
176176
ServerContextTakeover = false
177177
}
@@ -196,7 +196,7 @@ public async Task TwoDeflateBlocksInOneMessage()
196196
WebSocketTestStream stream = new();
197197
using WebSocket websocket = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
198198
{
199-
DangerousDeflateOptions = new()
199+
DangerousDeflateOptions = new WebSocketDeflateOptions()
200200
});
201201
// The first 3 octets(0xf2 0x48 0x05) and the least significant two
202202
// bits of the 4th octet(0x00) constitute one DEFLATE block with
@@ -285,14 +285,14 @@ public async Task LargeMessageSplitInMultipleFrames(int windowBits)
285285
using WebSocket server = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
286286
{
287287
IsServer = true,
288-
DangerousDeflateOptions = new()
288+
DangerousDeflateOptions = new WebSocketDeflateOptions()
289289
{
290290
ClientMaxWindowBits = windowBits
291291
}
292292
});
293293
using WebSocket client = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
294294
{
295-
DangerousDeflateOptions = new()
295+
DangerousDeflateOptions = new WebSocketDeflateOptions()
296296
{
297297
ClientMaxWindowBits = windowBits
298298
}
@@ -466,7 +466,7 @@ public async Task SendReceiveWithDifferentWindowBits(int clientWindowBits, int s
466466
using WebSocket server = WebSocket.CreateFromStream(stream, new WebSocketCreationOptions
467467
{
468468
IsServer = true,
469-
DangerousDeflateOptions = new()
469+
DangerousDeflateOptions = new WebSocketDeflateOptions()
470470
{
471471
ClientContextTakeover = false,
472472
ClientMaxWindowBits = clientWindowBits,
@@ -476,7 +476,7 @@ public async Task SendReceiveWithDifferentWindowBits(int clientWindowBits, int s
476476
});
477477
using WebSocket client = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
478478
{
479-
DangerousDeflateOptions = new()
479+
DangerousDeflateOptions = new WebSocketDeflateOptions()
480480
{
481481
ClientContextTakeover = false,
482482
ClientMaxWindowBits = clientWindowBits,
@@ -568,7 +568,7 @@ public async Task AutobahnTestCase13_3_1()
568568
{
569569
IsServer = true,
570570
KeepAliveInterval = TimeSpan.Zero,
571-
DangerousDeflateOptions = new()
571+
DangerousDeflateOptions = new WebSocketDeflateOptions()
572572
{
573573
ClientMaxWindowBits = 9,
574574
ServerMaxWindowBits = 9
@@ -577,7 +577,7 @@ public async Task AutobahnTestCase13_3_1()
577577
using WebSocket client = WebSocket.CreateFromStream(stream.Remote, new WebSocketCreationOptions
578578
{
579579
KeepAliveInterval = TimeSpan.Zero,
580-
DangerousDeflateOptions = new()
580+
DangerousDeflateOptions = new WebSocketDeflateOptions()
581581
{
582582
ClientMaxWindowBits = 9,
583583
ServerMaxWindowBits = 9
@@ -609,7 +609,7 @@ public async Task CompressedMessageWithEmptyLastFrame()
609609
{
610610
IsServer = true,
611611
KeepAliveInterval = TimeSpan.Zero,
612-
DangerousDeflateOptions = new()
612+
DangerousDeflateOptions = new WebSocketDeflateOptions()
613613
});
614614

615615
byte[] frame1 = new byte[1024];
@@ -626,7 +626,7 @@ public async Task CompressedMessageWithEmptyLastFrame()
626626
{
627627
IsServer = false,
628628
KeepAliveInterval = TimeSpan.Zero,
629-
DangerousDeflateOptions = new()
629+
DangerousDeflateOptions = new WebSocketDeflateOptions()
630630
});
631631

632632
int messageSize = 0;

src/libraries/System.Private.CoreLib/src/System/DateTime.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second)
209209
else
210210
{
211211
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
212-
this = new(year, month, day, hour, minute, 59);
212+
this = new DateTime(year, month, day, hour, minute, 59);
213213
ValidateLeapSecond();
214214
}
215215
}
@@ -226,7 +226,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
226226
else
227227
{
228228
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
229-
this = new(year, month, day, hour, minute, 59, kind);
229+
this = new DateTime(year, month, day, hour, minute, 59, kind);
230230
ValidateLeapSecond();
231231
}
232232
}
@@ -243,7 +243,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
243243
else
244244
{
245245
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
246-
this = new(year, month, day, hour, minute, 59, calendar);
246+
this = new DateTime(year, month, day, hour, minute, 59, calendar);
247247
ValidateLeapSecond();
248248
}
249249
}
@@ -265,7 +265,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
265265
else
266266
{
267267
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
268-
this = new(year, month, day, hour, minute, 59, millisecond);
268+
this = new DateTime(year, month, day, hour, minute, 59, millisecond);
269269
ValidateLeapSecond();
270270
}
271271
}
@@ -285,7 +285,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
285285
else
286286
{
287287
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
288-
this = new(year, month, day, hour, minute, 59, millisecond, kind);
288+
this = new DateTime(year, month, day, hour, minute, 59, millisecond, kind);
289289
ValidateLeapSecond();
290290
}
291291
}
@@ -302,7 +302,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
302302
else
303303
{
304304
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
305-
this = new(year, month, day, hour, minute, 59, millisecond, calendar);
305+
this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar);
306306
ValidateLeapSecond();
307307
}
308308
}
@@ -320,7 +320,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second,
320320
else
321321
{
322322
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
323-
this = new(year, month, day, hour, minute, 59, millisecond, calendar, kind);
323+
this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar, kind);
324324
ValidateLeapSecond();
325325
}
326326
}

src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -389,11 +389,11 @@ private static NullableAttributeStateParser CreateParser(IList<CustomAttributeDa
389389
attribute.AttributeType.Namespace == CompilerServicesNameSpace &&
390390
attribute.ConstructorArguments.Count == 1)
391391
{
392-
return new(attribute.ConstructorArguments[0].Value);
392+
return new NullableAttributeStateParser(attribute.ConstructorArguments[0].Value);
393393
}
394394
}
395395

396-
return new(null);
396+
return new NullableAttributeStateParser(null);
397397
}
398398

399399
private void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability)

src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Windows.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ private static Interop.BOOL HandlerRoutine(int dwCtrlType)
9999
{
100100
if (token.Signal == signal)
101101
{
102-
(tokens ??= new()).Add(token);
102+
(tokens ??= new List<Token>()).Add(token);
103103
}
104104
}
105105
}

0 commit comments

Comments
 (0)