Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace ca1720
{
//<snippet1>
// This code violates the rule.
public class Short
{
public int Int32 { get; set; }
public Guid Guid { get; set; }

public void Float(int int32) { }
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;

namespace ca1725
{
//<snippet1>
public interface IUserService
{
int GetAge(int id);
}

public class UserService : IUserService
{
// Violates CA1725: Parameter name should match the base declaration ('id')
// for consistency with IUserService
public int GetAge(int userId)
{
throw new NotImplementedException();
}
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.Extensions.Logging;

namespace ca1727
{
//<snippet1>
public class UserService
{
private readonly ILogger<UserService> _logger;

public UserService(ILogger<UserService> logger)
{
_logger = logger;
}

public void Create(string firstName, string lastName)
{
// This code violates the rule.
_logger.LogInformation("Creating user {firstName} {lastName}", firstName, lastName);

// This code satisfies the rule.
_logger.LogInformation("Creating user {FirstName} {LastName}", firstName, lastName);
}
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;

namespace ca1822
{
//<snippet1>
public class Printer
{
private readonly List<char> _items = [
'H', 'e', 'l', 'l', 'o',
];

public void PrintHello()
{
BadPrintHelloInternal();
GoodPrintHelloInternal();
GoodPrintHelloStaticInternal();
}

// This method violates the rule.
private void BadPrintHelloInternal()
{
Console.WriteLine("Hello");
}

// This methods satisfies the rule.
private void GoodPrintHelloInternal()
{
Console.WriteLine(string.Join(string.Empty, this._items));
}

private static void GoodPrintHelloStaticInternal()
{
Console.WriteLine("Hello");
}
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace ca1823
{
//<snippet1>
public class User
{
private readonly string _firstName;
private readonly string _lastName;

// CA1823: Unused field '_age'
private readonly int _age;

public User(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
}

public string GetFullName()
{
return $"My name is {_firstName} {_lastName}";
}
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace ca1844
{
//<snippet1>
// This class violates the rule.
public class BadStream : Stream
{
private readonly Stream _innerStream;

public BadStream(Stream innerStream)
{
_innerStream = innerStream;
}

public override bool CanRead => _innerStream.CanRead;
public override bool CanSeek => _innerStream.CanSeek;
public override bool CanWrite => _innerStream.CanWrite;
public override long Length => _innerStream.Length;
public override long Position { get => _innerStream.Position; set => _innerStream.Position = value; }

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// ...
return await _innerStream.ReadAsync(buffer, offset, count, cancellationToken);
}

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// ...
await _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
}

// Other required overrides
public override void Flush() => _innerStream.Flush();
public override int Read(byte[] buffer, int offset, int count) => _innerStream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => _innerStream.Seek(offset, origin);
public override void SetLength(long value) => _innerStream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => _innerStream.Write(buffer, offset, count);
}

// This class satisfies the rule.
public class GoodStream : Stream
{
private readonly Stream _innerStream;

public GoodStream(Stream innerStream)
{
_innerStream = innerStream;
}

public override bool CanRead => _innerStream.CanRead;
public override bool CanSeek => _innerStream.CanSeek;
public override bool CanWrite => _innerStream.CanWrite;
public override long Length => _innerStream.Length;
public override long Position { get => _innerStream.Position; set => _innerStream.Position = value; }

public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
// ...
return await _innerStream.ReadAsync(buffer, cancellationToken);
}

public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
// ...
await _innerStream.WriteAsync(buffer, cancellationToken);
}

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return await this.ReadAsync(buffer.AsMemory(offset, count), cancellationToken);
}

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await this.WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
}

// Other required overrides
public override void Flush() => _innerStream.Flush();
public override int Read(byte[] buffer, int offset, int count) => _innerStream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => _innerStream.Seek(offset, origin);
public override void SetLength(long value) => _innerStream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => _innerStream.Write(buffer, offset, count);
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Threading;
using System.Threading.Tasks;

namespace ca2008
{
//<snippet1>
public class Example
{
public void ProcessData()
{
// This code violates the rule.
var badTask = Task.Factory.StartNew(
() =>
{
// ...
}
);
badTask.ContinueWith(
t =>
{
// ...
}
);

// This code satisfies the rule.
var goodTask = Task.Factory.StartNew(
() =>
{
// ...
},
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default
);
goodTask.ContinueWith(
t =>
{
// ...
},
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default
);
}
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Threading.Tasks;

namespace ca2012
{
//<snippet1>
public class NumberValueTask
{
public async ValueTask<int> GetNumberAsync()
{
await Task.Delay(100);
return 123;
}

public async Task UseValueTaskIncorrectlyAsync()
{
// This code violates the rule,
// because ValueTask is awaited multiple times
ValueTask<int> numberValueTask = GetNumberAsync();

int first = await numberValueTask;
int second = await numberValueTask; // <- illegal reuse

// ...
}

// This code satisfies the rule.
public async Task UseValueTaskCorrectlyAsync()
{
int first = await GetNumberAsync();
int second = await GetNumberAsync();

// ..
}

public async Task UseValueTaskAsTaskAsync()
{
ValueTask<int> numberValueTask = GetNumberAsync();

Task<int> numberTask = numberValueTask.AsTask();

int first = await numberTask;
int second = await numberTask;

// ...
}
}
//</snippet1>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;

namespace ca2014
{
public class Example
{
//<snippet1>
// This method violates the rule.
public void ProcessDataBad()
{
for (int i = 0; i < 100; i++)
{
// CA2014: Potential stack overflow.
// Move the stackalloc out of the loop.
Span<int> buffer = stackalloc int[100];
buffer[0] = i;

// ...
}
}

// This method satisfies the rule.
public void ProcessDataGood()
{
Span<int> buffer = stackalloc int[100];

for (int i = 0; i < 100; i++)
{
buffer[0] = i;

// ...
}
}
//</snippet1>
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;

namespace ca2201
{
//<snippet1>
public class ExampleClass
{
public void BadMethod()
{
// This code violates the rule.
throw new Exception();
throw new NullReferenceException();
throw new IndexOutOfRangeException();
// ...
}

public void GoodMethod()
{
// This code satisfies the rule.
throw new ArgumentException();
throw new ArgumentNullException();
throw new InvalidOperationException();
// ...
}

// A minimal implementation of inheritance from Exception
public class CustomException : Exception { }

public void AnotherGoodMethod()
{
// Or create your own type that derives from Exception
// This code satisfies the rule too.
throw new CustomException();
}
}
//</snippet1>
}
Loading
Loading