content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Security.Latest.Inputs { /// <summary> /// Details of the On Premise resource that was assessed /// </summary> public sealed class OnPremiseResourceDetailsArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the machine /// </summary> [Input("machineName", required: true)] public Input<string> MachineName { get; set; } = null!; /// <summary> /// The platform where the assessed resource resides /// </summary> [Input("source", required: true)] public Input<string> Source { get; set; } = null!; /// <summary> /// The oms agent Id installed on the machine /// </summary> [Input("sourceComputerId", required: true)] public Input<string> SourceComputerId { get; set; } = null!; /// <summary> /// The unique Id of the machine /// </summary> [Input("vmuuid", required: true)] public Input<string> Vmuuid { get; set; } = null!; /// <summary> /// Azure resource Id of the workspace the machine is attached to /// </summary> [Input("workspaceId", required: true)] public Input<string> WorkspaceId { get; set; } = null!; public OnPremiseResourceDetailsArgs() { } } }
31.113208
81
0.597938
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Security/Latest/Inputs/OnPremiseResourceDetailsArgs.cs
1,649
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Threading; using static Interop; using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; namespace System.Windows.Forms { /// <summary> /// Provides methods to place data on and retrieve data from the system clipboard. This class cannot be inherited. /// </summary> public static class Clipboard { /// <summary> /// Places nonpersistent data on the system <see cref='Clipboard'/>. /// </summary> public static void SetDataObject(object data) { SetDataObject(data, false); } /// <summary> /// Overload that uses default values for retryTimes and retryDelay. /// </summary> public static void SetDataObject(object data, bool copy) { SetDataObject(data, copy, retryTimes: 10, retryDelay: 100); } /// <summary> /// Places data on the system <see cref='Clipboard'/> and uses copy to specify whether the data /// should remain on the <see cref='Clipboard'/> after the application exits. /// </summary> public static void SetDataObject(object data, bool copy, int retryTimes, int retryDelay) { if (Application.OleRequired() != ApartmentState.STA) { throw new Threading.ThreadStateException(SR.ThreadMustBeSTA); } if (data is null) { throw new ArgumentNullException(nameof(data)); } if (retryTimes < 0) { throw new ArgumentOutOfRangeException(nameof(retryTimes), retryTimes, string.Format(SR.InvalidLowBoundArgumentEx, nameof(retryTimes), retryTimes, 0)); } if (retryDelay < 0) { throw new ArgumentOutOfRangeException(nameof(retryDelay), retryDelay, string.Format(SR.InvalidLowBoundArgumentEx, nameof(retryDelay), retryDelay, 0)); } DataObject dataObject = null; if (!(data is IComDataObject)) { dataObject = new DataObject(data); } HRESULT hr; int retry = retryTimes; do { if (data is IComDataObject ido) { hr = Ole32.OleSetClipboard(ido); } else { hr = Ole32.OleSetClipboard(dataObject); } if (hr != HRESULT.S_OK) { if (retry == 0) { throw new ExternalException(SR.ClipboardOperationFailed, (int)hr); } retry--; Thread.Sleep(millisecondsTimeout: retryDelay); } } while (hr != 0); if (copy) { retry = retryTimes; do { hr = Ole32.OleFlushClipboard(); if (hr != HRESULT.S_OK) { if (retry == 0) { throw new ExternalException(SR.ClipboardOperationFailed, (int)hr); } retry--; Thread.Sleep(millisecondsTimeout: retryDelay); } } while (hr != 0); } } /// <summary> /// Retrieves the data that is currently on the system <see cref='Clipboard'/>. /// </summary> public static IDataObject GetDataObject() { if (Application.OleRequired() != ApartmentState.STA) { // Only throw if a message loop was started. This makes the case of trying // to query the clipboard from your finalizer or non-ui MTA thread // silently fail, instead of making your app die. // // however, if you are trying to write a normal windows forms app and // forget to set the STAThread attribute, we will correctly report // an error to aid in debugging. if (Application.MessageLoop) { throw new ThreadStateException(SR.ThreadMustBeSTA); } return null; } // We need to retry the GetDataObject() since the clipBoard is busy sometimes and hence the GetDataObject would fail with ClipBoardException. return GetDataObject(retryTimes: 10, retryDelay: 100); } /// <remarks> /// Private method to help accessing clipBoard for know retries before failing. /// </remarks> private static IDataObject GetDataObject(int retryTimes, int retryDelay) { IComDataObject dataObject = null; HRESULT hr; int retry = retryTimes; do { hr = Ole32.OleGetClipboard(ref dataObject); if (hr != HRESULT.S_OK) { if (retry == 0) { throw new ExternalException(SR.ClipboardOperationFailed, (int)hr); } retry--; Thread.Sleep(millisecondsTimeout: retryDelay); } } while (hr != 0); if (dataObject is not null) { if (dataObject is IDataObject ido && !Marshal.IsComObject(dataObject)) { return ido; } return new DataObject(dataObject); } return null; } public static void Clear() { Clipboard.SetDataObject(new DataObject()); } public static bool ContainsAudio() { IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetDataPresent(DataFormats.WaveAudio, false); } return false; } public static bool ContainsData(string format) { if (string.IsNullOrWhiteSpace(format)) { return false; } IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetDataPresent(format, false); } return false; } public static bool ContainsFileDropList() { IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetDataPresent(DataFormats.FileDrop, true); } return false; } public static bool ContainsImage() { IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetDataPresent(DataFormats.Bitmap, true); } return false; } public static bool ContainsText() => ContainsText(TextDataFormat.UnicodeText); public static bool ContainsText(TextDataFormat format) { SourceGenerated.EnumValidator.Validate(format, nameof(format)); IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetDataPresent(ConvertToDataFormats(format), false); } return false; } public static Stream GetAudioStream() { IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetData(DataFormats.WaveAudio, false) as Stream; } return null; } public static object GetData(string format) { if (string.IsNullOrWhiteSpace(format)) { return null; } IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetData(format); } return null; } public static StringCollection GetFileDropList() { IDataObject dataObject = Clipboard.GetDataObject(); StringCollection retVal = new StringCollection(); if (dataObject is not null) { if (dataObject.GetData(DataFormats.FileDrop, true) is string[] strings) { retVal.AddRange(strings); } } return retVal; } public static Image GetImage() { IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { return dataObject.GetData(DataFormats.Bitmap, true) as Image; } return null; } public static string GetText() => GetText(TextDataFormat.UnicodeText); public static string GetText(TextDataFormat format) { SourceGenerated.EnumValidator.Validate(format, nameof(format)); IDataObject dataObject = Clipboard.GetDataObject(); if (dataObject is not null) { if (dataObject.GetData(ConvertToDataFormats(format), false) is string text) { return text; } } return string.Empty; } public static void SetAudio(byte[] audioBytes) { if (audioBytes is null) { throw new ArgumentNullException(nameof(audioBytes)); } SetAudio(new MemoryStream(audioBytes)); } public static void SetAudio(Stream audioStream) { if (audioStream is null) { throw new ArgumentNullException(nameof(audioStream)); } IDataObject dataObject = new DataObject(); dataObject.SetData(DataFormats.WaveAudio, false, audioStream); Clipboard.SetDataObject(dataObject, true); } public static void SetData(string format, object data) { if (string.IsNullOrWhiteSpace(format)) { if (format is null) { throw new ArgumentNullException(nameof(format)); } throw new ArgumentException(SR.DataObjectWhitespaceEmptyFormatNotAllowed, nameof(format)); } // Note: We delegate argument checking to IDataObject.SetData, if it wants to do so. IDataObject dataObject = new DataObject(); dataObject.SetData(format, data); Clipboard.SetDataObject(dataObject, true); } public static void SetFileDropList(StringCollection filePaths) { if (filePaths is null) { throw new ArgumentNullException(nameof(filePaths)); } if (filePaths.Count == 0) { throw new ArgumentException(SR.CollectionEmptyException); } // Validate the paths to make sure they don't contain invalid characters foreach (string path in filePaths) { try { Path.GetFullPath(path); } catch (Exception e) when (!ClientUtils.IsCriticalException(e)) { throw new ArgumentException(string.Format(SR.Clipboard_InvalidPath, path, "filePaths"), e); } } if (filePaths.Count > 0) { IDataObject dataObject = new DataObject(); string[] strings = new string[filePaths.Count]; filePaths.CopyTo(strings, 0); dataObject.SetData(DataFormats.FileDrop, true, strings); Clipboard.SetDataObject(dataObject, true); } } public static void SetImage(Image image) { if (image is null) { throw new ArgumentNullException(nameof(image)); } IDataObject dataObject = new DataObject(); dataObject.SetData(DataFormats.Bitmap, true, image); Clipboard.SetDataObject(dataObject, true); } public static void SetText(string text) => SetText(text, TextDataFormat.UnicodeText); public static void SetText(string text, TextDataFormat format) { if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException(nameof(text)); } SourceGenerated.EnumValidator.Validate(format, nameof(format)); IDataObject dataObject = new DataObject(); dataObject.SetData(ConvertToDataFormats(format), false, text); Clipboard.SetDataObject(dataObject, true); } private static string ConvertToDataFormats(TextDataFormat format) { switch (format) { case TextDataFormat.Text: return DataFormats.Text; case TextDataFormat.UnicodeText: return DataFormats.UnicodeText; case TextDataFormat.Rtf: return DataFormats.Rtf; case TextDataFormat.Html: return DataFormats.Html; case TextDataFormat.CommaSeparatedValue: return DataFormats.CommaSeparatedValue; } return DataFormats.UnicodeText; } } }
31.821826
166
0.523306
[ "MIT" ]
jsoref/dotnet-winforms
src/System.Windows.Forms/src/System/Windows/Forms/Clipboard.cs
14,290
C#
using System.Collections.Generic; namespace MsgReader.Rtf { internal class ListOverrideTable : List<ListOverride> { #region GetById public ListOverride GetById(int id) { foreach (var listOverride in this) { if (listOverride.Id == id) return listOverride; } return null; } #endregion } internal class ListOverride { #region Properties public int ListId { get; set; } /// <summary> /// List override count /// </summary> public int ListOverrideCount { get; set; } /// <summary> /// Internal Id /// </summary> public int Id { get; set; } #endregion #region Constructor public ListOverride() { Id = 1; ListOverrideCount = 0; ListId = 0; } #endregion #region ToString public override string ToString() { return "ID:" + Id + " ListID:" + ListId + " Count:" + ListOverrideCount; } #endregion } }
22.288462
84
0.486626
[ "MIT" ]
seppu/EWSAsposePDFDemo
MsgReader/Rtf/ListOverrideTable.cs
1,161
C#
using DevExpress.XtraCharts; using DevExpress.XtraCharts.Native; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; namespace SpreadCommander.Common.PowerShell.CmdLets.Charts.SeriesContext { public class NestedDoughnutSeriesContext: DoughnutSeriesContext { [Parameter(HelpMessage = "Specifies a group for all series having the same nested group value.")] public int? Group { get; set; } [Parameter(HelpMessage = "Inner indent between the outer and inner edges of nested doughnuts.")] public double? InnerIndent { get; set; } [Parameter(HelpMessage = "Nested doughnut's size, in respect to the sizes of other nested doughnuts.")] public double? Weight { get; set; } public override void SetupXtraChartSeries(ChartContext chartContext, Series series) { base.SetupXtraChartSeries(chartContext, series); if (series.View is not NestedDoughnutSeriesView viewDoughnut) return; if (InnerIndent.HasValue) viewDoughnut.InnerIndent = InnerIndent.Value; if (Weight.HasValue) viewDoughnut.Weight = Weight.Value; } public override void BoundDataChanged(ChartContext chartContext, Series series) { base.BoundDataChanged(chartContext, series); if (series.View is NestedDoughnutSeriesView view) { if (Group.HasValue) view.Group = Group.Value; } } } }
28.959184
105
0.75828
[ "Apache-2.0" ]
VassilievVV/SpreadCommander
SpreadCommander.Common/PowerShell/CmdLets/Charts/SeriesContext/NestedDoughnutSeriesContext.cs
1,421
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Entity; namespace HOSS { public partial class Messages : System.Web.UI.Page { UsersEntities3 dbcont = new UsersEntities3(); protected void Page_Load(object sender, EventArgs e) { try { string username = Context.User.Identity.Name; dbcont.PatientTables.Load(); PatientTable patient = (from x in dbcont.PatientTables.Local where (x.UserName.Equals(username)) select x).First(); dbcont.MsgTables.Load(); var co = from x in dbcont.MsgTables.Local where x.FromUserName.Equals(username) select x; GridView1.DataSource = co; GridView1.DataBind(); } catch { Response.Redirect("~/Doctors/DocMessages.aspx"); } } protected void sendButton_Click(object sender, EventArgs e) { using (UsersEntities3 dbcon = new UsersEntities3()) { MsgTable msg = new MsgTable(); msg.ToUserName = DropDownList1.Text; msg.MsgDate = DateTime.Now; msg.MsgText = msgTextbox.Text; msg.FromUserName = HttpContext.Current.User.Identity.Name.ToString(); // add data to the dbcon dbcon.MsgTables.Add(msg); dbcon.SaveChanges(); } Response.Redirect(Request.RawUrl); } protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { } protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e) { } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { } } }
26.207317
97
0.530945
[ "Apache-2.0" ]
BryceSuchy/Hospital-Online-Scheduling-System
WebApplication1/HOSS/mywork/Messages.aspx.cs
2,151
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel; using Microsoft.AspNet.WebHooks.Config; namespace System.Web.Http { /// <summary> /// Extension methods for <see cref="HttpConfiguration"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class HttpConfigurationExtensions { /// <summary> /// Initializes support for receiving generic WebHooks containing valid JSON /// with no special validation logic or security requirements. This can for example be used /// to receive WebHooks from IFTTT's Maker Channel or a Zapier WebHooks Action. /// A sample WebHook URI is '<c>https://&lt;host&gt;/api/webhooks/incoming/genericjson/{id}?code=83699ec7c1d794c0c780e49a5c72972590571fd8</c>'. /// For security reasons the WebHook URI must be an <c>https</c> URI and contain a 'code' query parameter with the /// same value as configured in the '<c>MS_WebHookReceiverSecret_GenericJson</c>' application setting, optionally using IDs /// to differentiate between multiple WebHooks, for example '<c>secret0, id1=secret1, id2=secret2</c>'. /// The 'code' parameter must be between 32 and 128 characters long. /// The URI may optionally include an '<c>action</c>' query parameter which will serve as the WebHook action. /// </summary> /// <param name="config">The current <see cref="HttpConfiguration"/>config.</param> public static void InitializeReceiveGenericJsonWebHooks(this HttpConfiguration config) { WebHooksConfig.Initialize(config); } } }
53.636364
151
0.69887
[ "Apache-2.0" ]
Mythz123/AspNetWebHooks
src/Microsoft.AspNet.WebHooks.Receivers.Generic/Extensions/HttpConfigurationExtensions.cs
1,772
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Configuration.Assemblies; using System.IO; using System.Runtime.Serialization; using System.Text; using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection { public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { // If you modify any of these fields, you must also update the // AssemblyBaseObject structure in object.h private string _name; private byte[] _publicKey; private byte[] _publicKeyToken; private CultureInfo _cultureInfo; private string _codeBase; private Version _version; private StrongNameKeyPair _strongNameKeyPair; private AssemblyHashAlgorithm _hashAlgorithm; private AssemblyVersionCompatibility _versionCompatibility; private AssemblyNameFlags _flags; public AssemblyName() { _hashAlgorithm = AssemblyHashAlgorithm.None; _versionCompatibility = AssemblyVersionCompatibility.SameMachine; _flags = AssemblyNameFlags.None; } // Set and get the name of the assembly. If this is a weak Name // then it optionally contains a site. For strong assembly names, // the name partitions up the strong name's namespace public string Name { get { return _name; } set { _name = value; } } public Version Version { get { return _version; } set { _version = value; } } // Locales, internally the LCID is used for the match. public CultureInfo CultureInfo { get { return _cultureInfo; } set { _cultureInfo = value; } } public string CultureName { get { return (_cultureInfo == null) ? null : _cultureInfo.Name; } set { _cultureInfo = (value == null) ? null : new CultureInfo(value); } } public string CodeBase { get { return _codeBase; } set { _codeBase = value; } } public string EscapedCodeBase { get { if (_codeBase == null) return null; else return EscapeCodeBase(_codeBase); } } public ProcessorArchitecture ProcessorArchitecture { get { int x = (((int)_flags) & 0x70) >> 4; if (x > 5) x = 0; return (ProcessorArchitecture)x; } set { int x = ((int)value) & 0x07; if (x <= 5) { _flags = (AssemblyNameFlags)((int)_flags & 0xFFFFFF0F); _flags |= (AssemblyNameFlags)(x << 4); } } } public AssemblyContentType ContentType { get { int x = (((int)_flags) & 0x00000E00) >> 9; if (x > 1) x = 0; return (AssemblyContentType)x; } set { int x = ((int)value) & 0x07; if (x <= 1) { _flags = (AssemblyNameFlags)((int)_flags & 0xFFFFF1FF); _flags |= (AssemblyNameFlags)(x << 9); } } } // Make a copy of this assembly name. public object Clone() { var name = new AssemblyName { _name = _name, _publicKey = (byte[])_publicKey?.Clone(), _publicKeyToken = (byte[])_publicKeyToken?.Clone(), _cultureInfo = _cultureInfo, _version = (Version)_version?.Clone(), _flags = _flags, _codeBase = _codeBase, _hashAlgorithm = _hashAlgorithm, _versionCompatibility = _versionCompatibility, }; return name; } /* * Get the AssemblyName for a given file. This will only work * if the file contains an assembly manifest. This method causes * the file to be opened and closed. */ public static AssemblyName GetAssemblyName(string assemblyFile) { if (assemblyFile == null) throw new ArgumentNullException(nameof(assemblyFile)); return GetFileInformationCore(assemblyFile); } public byte[] GetPublicKey() { return _publicKey; } public void SetPublicKey(byte[] publicKey) { _publicKey = publicKey; if (publicKey == null) _flags &= ~AssemblyNameFlags.PublicKey; else _flags |= AssemblyNameFlags.PublicKey; } // The compressed version of the public key formed from a truncated hash. // Will throw a SecurityException if _publicKey is invalid public byte[] GetPublicKeyToken() { if (_publicKeyToken == null) _publicKeyToken = ComputePublicKeyToken(); return _publicKeyToken; } public void SetPublicKeyToken(byte[] publicKeyToken) { _publicKeyToken = publicKeyToken; } // Flags modifying the name. So far the only flag is PublicKey, which // indicates that a full public key and not the compressed version is // present. // Processor Architecture flags are set only through ProcessorArchitecture // property and can't be set or retrieved directly // Content Type flags are set only through ContentType property and can't be // set or retrieved directly public AssemblyNameFlags Flags { get { return (AssemblyNameFlags)((uint)_flags & 0xFFFFF10F); } set { _flags &= unchecked((AssemblyNameFlags)0x00000EF0); _flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F)); } } public AssemblyHashAlgorithm HashAlgorithm { get { return _hashAlgorithm; } set { _hashAlgorithm = value; } } public AssemblyVersionCompatibility VersionCompatibility { get { return _versionCompatibility; } set { _versionCompatibility = value; } } public StrongNameKeyPair KeyPair { get { return _strongNameKeyPair; } set { _strongNameKeyPair = value; } } public string FullName { get { if (this.Name == null) return string.Empty; // Do not call GetPublicKeyToken() here - that latches the result into AssemblyName which isn't a side effect we want. byte[] pkt = _publicKeyToken ?? ComputePublicKeyToken(); return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); } } public override string ToString() { string s = FullName; if (s == null) return base.ToString(); else return s; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public void OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } /// <summary> /// Compares the simple names disregarding Version, Culture and PKT. While this clearly does not /// match the intent of this api, this api has been broken this way since its debut and we cannot /// change its behavior now. /// </summary> public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) { if (object.ReferenceEquals(reference, definition)) return true; if (reference == null) throw new ArgumentNullException(nameof(reference)); if (definition == null) throw new ArgumentNullException(nameof(definition)); string refName = reference.Name ?? string.Empty; string defName = definition.Name ?? string.Empty; return refName.Equals(defName, StringComparison.OrdinalIgnoreCase); } internal static string EscapeCodeBase(string codebase) { if (codebase == null) return string.Empty; int position = 0; char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return codebase; return new string(dest, 0, position); } // This implementation of EscapeString has been copied from System.Private.Uri from corefx repo // - forceX characters are always escaped if found // - rsvd character will remain unescaped // // start - starting offset from input // end - the exclusive ending offset in input // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. // // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // internal static unsafe char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { int i = start; int prevInputPos = start; byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160 fixed (char* pStr = input) { for (; i < end; ++i) { char ch = pStr[i]; // a Unicode ? if (ch > '\x7F') { short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1); short count = 1; for (; count < maxSize && pStr[i + count] > '\x7f'; ++count) ; // Is the last a high surrogate? if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF) { // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair if (count == 1 || count == end - i) throw new FormatException(SR.Arg_FormatException); // need to grab one more char as a Surrogate except when it's a bogus input ++count; } dest = EnsureDestinationSize(pStr, dest, i, (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte), c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte, ref destPos, prevInputPos); short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes, c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar); // This is the only exception that built in UriParser can throw after a Uri ctor. // Should not happen unless the app tries to feed an invalid Unicode string if (numberOfBytes == 0) throw new FormatException(SR.Arg_FormatException); i += (count - 1); for (count = 0; count < numberOfBytes; ++count) EscapeAsciiChar((char)bytes[count], dest, ref destPos); prevInputPos = i + 1; } else if (ch == '%' && rsvd == '%') { // Means we don't reEncode '%' but check for the possible escaped sequence dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != c_DummyChar) { // leave it escaped dest[destPos++] = '%'; dest[destPos++] = pStr[i + 1]; dest[destPos++] = pStr[i + 2]; i += 2; } else { EscapeAsciiChar('%', dest, ref destPos); } prevInputPos = i + 1; } else if (ch == force1 || ch == force2) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch))) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } } if (prevInputPos != i) { // need to fill up the dest array ? if (prevInputPos != start || dest != null) dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); } } return dest; } // // ensure destination array has enough space and contains all the needed input stuff // private static unsafe char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; if ((object)dest != null && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } // ensuring we copied everything form the input string left before last escaping while (prevInputPos != currentInputPos) dest[destPos++] = pStr[prevInputPos++]; return dest; } internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { to[pos++] = '%'; to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4]; to[pos++] = s_hexUpperChars[ch & 0xf]; } internal static char EscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return c_DummyChar; } int res = (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return c_DummyChar; } return (char)((res << 4) + ((next <= '9') ? ((int)next - (int)'0') : (((next <= 'F') ? ((int)next - (int)'A') : ((int)next - (int)'a')) + 10))); } private static bool IsReservedUnreservedOrHash(char c) { if (IsUnreserved(c)) { return true; } return (RFC3986ReservedMarks.Contains(c)); } internal static bool IsUnreserved(char c) { if (IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.Contains(c)); } //Only consider ASCII characters internal static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } internal static bool IsAsciiLetterOrDigit(char character) { return IsAsciiLetter(character) || (character >= '0' && character <= '9'); } private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; internal const char c_DummyChar = (char)0xFFFF; //An Invalid Unicode character used as a dummy char passed into the parameter private const short c_MaxAsciiCharsReallocate = 40; private const short c_MaxUnicodeCharsReallocate = 40; private const short c_MaxUTF_8BytesPerUnicodeChar = 4; private const short c_EncodedCharsPerByte = 3; private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; private const string RFC3986UnreservedMarks = @"-._~"; } }
37.720559
172
0.504392
[ "MIT" ]
mazong1123/coreclr
src/System.Private.CoreLib/shared/System/Reflection/AssemblyName.cs
18,898
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the connect-2017-08-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Connect.Model { /// <summary> /// Contains information about a hierarchy structure. /// </summary> public partial class HierarchyStructure { private HierarchyLevel _levelFive; private HierarchyLevel _levelFour; private HierarchyLevel _levelOne; private HierarchyLevel _levelThree; private HierarchyLevel _levelTwo; /// <summary> /// Gets and sets the property LevelFive. /// <para> /// Information about level five. /// </para> /// </summary> public HierarchyLevel LevelFive { get { return this._levelFive; } set { this._levelFive = value; } } // Check to see if LevelFive property is set internal bool IsSetLevelFive() { return this._levelFive != null; } /// <summary> /// Gets and sets the property LevelFour. /// <para> /// Information about level four. /// </para> /// </summary> public HierarchyLevel LevelFour { get { return this._levelFour; } set { this._levelFour = value; } } // Check to see if LevelFour property is set internal bool IsSetLevelFour() { return this._levelFour != null; } /// <summary> /// Gets and sets the property LevelOne. /// <para> /// Information about level one. /// </para> /// </summary> public HierarchyLevel LevelOne { get { return this._levelOne; } set { this._levelOne = value; } } // Check to see if LevelOne property is set internal bool IsSetLevelOne() { return this._levelOne != null; } /// <summary> /// Gets and sets the property LevelThree. /// <para> /// Information about level three. /// </para> /// </summary> public HierarchyLevel LevelThree { get { return this._levelThree; } set { this._levelThree = value; } } // Check to see if LevelThree property is set internal bool IsSetLevelThree() { return this._levelThree != null; } /// <summary> /// Gets and sets the property LevelTwo. /// <para> /// Information about level two. /// </para> /// </summary> public HierarchyLevel LevelTwo { get { return this._levelTwo; } set { this._levelTwo = value; } } // Check to see if LevelTwo property is set internal bool IsSetLevelTwo() { return this._levelTwo != null; } } }
27.916667
105
0.568792
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/Connect/Generated/Model/HierarchyStructure.cs
3,685
C#
//======= Copyright (c) Valve Corporation, All rights reserved. =============== // // Purpose: Collider dangling from the player's head // //============================================================================= using UnityEngine; using System.Collections; namespace Valve.VR.InteractionSystem { //------------------------------------------------------------------------- [RequireComponent( typeof( CapsuleCollider ) )] public class BodyCollider : MonoBehaviour { public Transform head; private CapsuleCollider capsuleCollider; //------------------------------------------------- void Awake() { capsuleCollider = GetComponent<CapsuleCollider>(); } //------------------------------------------------- void FixedUpdate() { float distanceFromFloor = Vector3.Dot( head.localPosition, Vector3.up ); capsuleCollider.height = Mathf.Max( capsuleCollider.radius, distanceFromFloor ); transform.localPosition = head.localPosition - 0.5f * distanceFromFloor * Vector3.up; } } }
29.25
89
0.51567
[ "MIT" ]
13rac1/SpaceNachosVR
Assets/SteamVR/InteractionSystem/Core/Scripts/BodyCollider.cs
1,055
C#
/* MIT License Copyright (c) Jeff Campbell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEditor; using UnityEngine; using UnityEngine.Networking; namespace JCMG.Genesis.Editor { /// <summary> /// Helper methods for checking remote SDK updates /// </summary> internal static class SDKUpdateTools { /// <summary> /// Json response fields from remote latest release /// </summary> private struct ResponseData { /// <summary> /// The SemVer tag of the latest release. /// </summary> #pragma warning disable 649 // ReSharper disable once InconsistentNaming public string tag_name; #pragma warning restore 649 } // Title private const string TITLE_FORMAT = "{0} Update"; // Body Content private const string UPDATE_AVAILABLE_BODY_FORMAT = "A newer version of {0} is available!\n\n" + "Currently installed version: {1}\n" + "New version: {2}"; private const string UP_TO_DATE_BODY_FORMAT = "{0} is up to date (v{1})."; private const string HAS_NEWER_VERSION_THAN_RELEASED_BODY_FORMAT = "Your {0} version seems to be newer than the latest release?!?\n\n" + "Currently installed version: {1}\n" + "Latest release: {2}"; private const string CANNOT_CONTACT_GITHUB_BODY_FORMAT = "Could not request latest {0} version!\n\n" + "Make sure that you are connected to the internet.\n"; // Button Prompts private const string OK_BUTTON = "OK"; private const string CANCEL_BUTTON = "Cancel"; private const string TRY_AGAIN_BUTTON = "Try Again"; private const string SHOW_IN_GITHUB_BUTTON = "Show in GitHub"; public static void CheckUpdateInfo(string sdkName, string githubLatestReleaseUrl) { var info = GetUpdateInfo(githubLatestReleaseUrl); DisplayUpdateInfo(info, sdkName, githubLatestReleaseUrl); } public static SDKUpdateInfo GetUpdateInfo(string githubLatestReleaseUrl) { var localVersion = GetLocalVersion(); var remoteVersion = GetRemoteVersion(githubLatestReleaseUrl); return new SDKUpdateInfo(localVersion, remoteVersion); } private static string GetLocalVersion() { return VersionConstants.VERSION; } private static string GetRemoteVersion(string githubLatestReleaseUrl) { try { return JsonUtility.FromJson<ResponseData>(RequestLatestRelease(githubLatestReleaseUrl)).tag_name; } catch { // ignored } return string.Empty; } private static string RequestLatestRelease(string githubLatestReleaseUrl) { var response = string.Empty; using (var www = UnityWebRequest.Get(githubLatestReleaseUrl)) { var asyncOperation = www.SendWebRequest(); while (!asyncOperation.isDone) { } if (!www.isNetworkError && !www.isHttpError) { response = asyncOperation.webRequest.downloadHandler.text; } } return response; } private static void DisplayUpdateInfo(SDKUpdateInfo info, string sdkName, string githubLatestReleaseUrl) { switch (info.updateState) { case SDKUpdateState.UpdateAvailable: if (EditorUtility.DisplayDialog( GetDialogTitle(sdkName), GetUpdateAvailableBody(sdkName, info), SHOW_IN_GITHUB_BUTTON, CANCEL_BUTTON)) { Application.OpenURL(githubLatestReleaseUrl); } break; case SDKUpdateState.UpToDate: EditorUtility.DisplayDialog( GetDialogTitle(sdkName), GetUpToDateBody(sdkName, info), OK_BUTTON); break; case SDKUpdateState.AheadOfLatestRelease: if (EditorUtility.DisplayDialog( GetDialogTitle(sdkName), GetNewerVersionWarningBody(sdkName, info), SHOW_IN_GITHUB_BUTTON, CANCEL_BUTTON)) { Application.OpenURL(githubLatestReleaseUrl); } break; case SDKUpdateState.NoConnection: if (EditorUtility.DisplayDialog( GetDialogTitle(sdkName), GetRemoteWarningBody(sdkName), TRY_AGAIN_BUTTON, CANCEL_BUTTON)) { CheckUpdateInfo(sdkName, githubLatestReleaseUrl); } break; } } private static string GetDialogTitle(string sdkName) { return string.Format(TITLE_FORMAT, sdkName); } private static string GetUpdateAvailableBody(string sdkName, SDKUpdateInfo updateInfo) { return string.Format( UPDATE_AVAILABLE_BODY_FORMAT, sdkName, updateInfo.localVersionString, updateInfo.remoteVersionString); } private static string GetUpToDateBody(string sdkName, SDKUpdateInfo updateInfo) { return string.Format(UP_TO_DATE_BODY_FORMAT, sdkName, updateInfo.localVersionString); } private static string GetNewerVersionWarningBody(string sdkName, SDKUpdateInfo updateInfo) { return string.Format( HAS_NEWER_VERSION_THAN_RELEASED_BODY_FORMAT, sdkName, updateInfo.localVersionString, updateInfo.remoteVersionString); } private static string GetRemoteWarningBody(string sdkName) { return string.Format(CANNOT_CONTACT_GITHUB_BODY_FORMAT, sdkName); } } }
29.339806
113
0.721707
[ "MIT" ]
TheHacky/Genesis
Unity/Assets/JCMG/Genesis/Scripts/Editor/Updates/SDKUpdateTools.cs
6,044
C#
using ProtoBuf; namespace Bunsan.Broker.Rabbit { [ProtoContract] class RabbitTask { [ProtoMember(1, IsRequired = false)] public string Identifier { get; set; } [ProtoMember(2, IsRequired = false)] public Task Task { get; set; } [ProtoMember(3, IsRequired = false)] public Constraints Constraints { get; set; } [ProtoMember(4, IsRequired = false)] public string StatusQueue { get; set; } [ProtoMember(5, IsRequired = false)] public string ResultQueue { get; set; } [ProtoMember(6, IsRequired = false)] public string ErrorQueue { get; set; } } }
24.555556
52
0.600302
[ "Apache-2.0" ]
bacsorg/bacs
bunsan/broker_net/Bunsan.Broker/Rabbit/RabbitTask.cs
665
C#
#region Licence /* The MIT License (MIT) Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Threading.Tasks; using FluentAssertions; using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles; using Paramore.Brighter.Core.Tests.ExceptionPolicy.TestDoubles; using Xunit; using Paramore.Brighter.Policies.Handlers; using Polly; using Polly.CircuitBreaker; using Polly.Registry; using Microsoft.Extensions.DependencyInjection; using Paramore.Brighter.Extensions.DependencyInjection; namespace Paramore.Brighter.Core.Tests.ExceptionPolicy { public class CommandProcessorWithCircuitBreakerAsyncTests { private readonly CommandProcessor _commandProcessor; private readonly MyCommand _myCommand = new MyCommand(); private Exception _thirdException; private Exception _firstException; private Exception _secondException; public CommandProcessorWithCircuitBreakerAsyncTests() { var registry = new SubscriberRegistry(); registry.RegisterAsync<MyCommand, MyFailsWithDivideByZeroHandlerAsync>(); var container = new ServiceCollection(); container.AddSingleton<MyFailsWithDivideByZeroHandlerAsync>(); container.AddSingleton<ExceptionPolicyHandlerAsync<MyCommand>>(); var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); var policyRegistry = new PolicyRegistry(); var policy = Policy .Handle<DivideByZeroException>() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); policyRegistry.Add("MyDivideByZeroPolicy", policy); MyFailsWithDivideByZeroHandlerAsync.ReceivedCommand = false; _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactoryAsync)handlerFactory, new InMemoryRequestContextFactory(), policyRegistry); } //We have to catch the final exception that bubbles out after retry [Fact] public async Task When_Sending_A_Command_That_Repeatedly_Fails_Break_The_Circuit_Async() { //First two should be caught, and increment the count _firstException = await Catch.ExceptionAsync(async () => await _commandProcessor.SendAsync(_myCommand)); _secondException = await Catch.ExceptionAsync(async () => await _commandProcessor.SendAsync(_myCommand)); //this one should tell us that the circuit is broken _thirdException = await Catch.ExceptionAsync(async () => await _commandProcessor.SendAsync(_myCommand)); //_should_send_the_command_to_the_command_handler MyFailsWithDivideByZeroHandlerAsync.ShouldReceive(_myCommand).Should().BeTrue(); //_should_bubble_up_the_first_exception _firstException.Should().BeOfType<DivideByZeroException>(); //_should_bubble_up_the_second_exception _secondException.Should().BeOfType<DivideByZeroException>(); //_should_break_the_circuit_after_two_fails _thirdException.Should().BeOfType<BrokenCircuitException>(); } } }
44.378947
157
0.745731
[ "MIT" ]
BuildJet/Brighter
tests/Paramore.Brighter.Core.Tests/ExceptionPolicy/When_Sending_A_Command_That_Repeatedely_Fails_Break_The_Circuit_Async.cs
4,227
C#
using Newtonsoft.Json; namespace Pipedrive.Models.Request { public class NewProductPrice { [JsonProperty("price")] public decimal Price { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("cost")] public decimal? Cost { get; set; } [JsonProperty("overhead_cost")] public decimal? OverheadCost { get; set; } } }
21.6
50
0.597222
[ "MIT" ]
jezloop/pipedrive-dotnet
src/Pipedrive.net/Models/Request/NewProductPrice.cs
434
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace NuGet.PackageManagement.UI { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NuGet.PackageManagement.UI.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Not sorted, press space to sort ascending. /// </summary> public static string Accessibility_ColumnNotSortedHelpText { get { return ResourceManager.GetString("Accessibility_ColumnNotSortedHelpText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Sorted ascending, press space to sort descending. /// </summary> public static string Accessibility_ColumnSortedAscendingHelpText { get { return ResourceManager.GetString("Accessibility_ColumnSortedAscendingHelpText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Sorted descending, press space to sort ascending. /// </summary> public static string Accessibility_ColumnSortedDescendingHelpText { get { return ResourceManager.GetString("Accessibility_ColumnSortedDescendingHelpText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package changes. /// </summary> public static string Accessibility_PackageChanges { get { return ResourceManager.GetString("Accessibility_PackageChanges", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package deprecation. /// </summary> public static string Accessibility_PackageDeprecation { get { return ResourceManager.GetString("Accessibility_PackageDeprecation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package details URL icon. /// </summary> public static string Accessibility_PackageDetailsUrlIcon { get { return ResourceManager.GetString("Accessibility_PackageDetailsUrlIcon", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package icon. /// </summary> public static string Accessibility_PackageIcon { get { return ResourceManager.GetString("Accessibility_PackageIcon", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} version {1}. /// </summary> public static string Accessibility_PackageIdentity { get { return ResourceManager.GetString("Accessibility_PackageIdentity", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package manager. /// </summary> public static string Accessibility_PackageManager { get { return ResourceManager.GetString("Accessibility_PackageManager", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package metadata. /// </summary> public static string Accessibility_PackageMetadata { get { return ResourceManager.GetString("Accessibility_PackageMetadata", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Packages. /// </summary> public static string Accessibility_Packages { get { return ResourceManager.GetString("Accessibility_Packages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package details. /// </summary> public static string Accessibility_PackagesDetails { get { return ResourceManager.GetString("Accessibility_PackagesDetails", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Packages list. /// </summary> public static string Accessibility_PackagesList { get { return ResourceManager.GetString("Accessibility_PackagesList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package vulnerabilities. /// </summary> public static string Accessibility_PackageVulnerabilities { get { return ResourceManager.GetString("Accessibility_PackageVulnerabilities", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prefix reserved. /// </summary> public static string Accessibility_PrefixReserved { get { return ResourceManager.GetString("Accessibility_PrefixReserved", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Promote all to top level dependencies. /// </summary> public static string Accessibility_PromoteAllToTopLevel { get { return ResourceManager.GetString("Accessibility_PromoteAllToTopLevel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Promote to a top level dependency. /// </summary> public static string Accessibility_PromoteToTopLevel { get { return ResourceManager.GetString("Accessibility_PromoteToTopLevel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use arrow keys to change the size of the sections. /// </summary> public static string Accessibility_ThumbHelp { get { return ResourceManager.GetString("Accessibility_ThumbHelp", resourceCulture); } } /// <summary> /// Looks up a localized string similar to splitter for Packages list. /// </summary> public static string Accessibility_ThumbName { get { return ResourceManager.GetString("Accessibility_ThumbName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package vulnerability description. /// </summary> public static string Accessibility_VulnerabilitiesDescriptionName { get { return ResourceManager.GetString("Accessibility_VulnerabilitiesDescriptionName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Consolidate. /// </summary> public static string Action_Consolidate { get { return ResourceManager.GetString("Action_Consolidate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Downgrade. /// </summary> public static string Action_Downgrade { get { return ResourceManager.GetString("Action_Downgrade", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Install. /// </summary> public static string Action_Install { get { return ResourceManager.GetString("Action_Install", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Update. /// </summary> public static string Action_Update { get { return ResourceManager.GetString("Action_Update", resourceCulture); } } /// <summary> /// Looks up a localized string similar to All. /// </summary> public static string AggregateSourceName { get { return ResourceManager.GetString("AggregateSourceName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Argument cannot be null or empty.. /// </summary> public static string ArgumentNullOrEmpty { get { return ResourceManager.GetString("ArgumentNullOrEmpty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Consider migrating this project&apos;s NuGet package management format from &apos;packages.config&apos; to &apos;PackageReference&apos;.. /// </summary> public static string AskForPRMigrator { get { return ResourceManager.GetString("AskForPRMigrator", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Some NuGet packages are missing from this solution. Click to restore from your online package sources.. /// </summary> public static string AskForRestoreMessage { get { return ResourceManager.GetString("AskForRestoreMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A new version of NuGet Package Manager is available.. /// </summary> public static string AskForUpdateMessage { get { return ResourceManager.GetString("AskForUpdateMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Implicitly referenced by an SDK. To update the package, update the SDK to which it belongs.. /// </summary> public static string AutoReferenced { get { return ResourceManager.GetString("AutoReferenced", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0:G3}B. /// </summary> public static string Billion { get { return ResourceManager.GetString("Billion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select a Package Source Folder. /// </summary> public static string BrowseFolderDialogDescription { get { return ResourceManager.GetString("BrowseFolderDialogDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select. /// </summary> public static string BrowseFolderDialogSelectButton { get { return ResourceManager.GetString("BrowseFolderDialogSelectButton", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Cancel. /// </summary> public static string Button_Cancel { get { return ResourceManager.GetString("Button_Cancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Co_py. /// </summary> public static string Button_Copy { get { return ResourceManager.GetString("Button_Copy", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Dismiss. /// </summary> public static string Button_Dismiss { get { return ResourceManager.GetString("Button_Dismiss", resourceCulture); } } /// <summary> /// Looks up a localized string similar to I _Accept. /// </summary> public static string Button_IAccept { get { return ResourceManager.GetString("Button_IAccept", resourceCulture); } } /// <summary> /// Looks up a localized string similar to I _Decline. /// </summary> public static string Button_IDecline { get { return ResourceManager.GetString("Button_IDecline", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Install. /// </summary> public static string Button_Install { get { return ResourceManager.GetString("Button_Install", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _No. /// </summary> public static string Button_No { get { return ResourceManager.GetString("Button_No", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No to A_ll. /// </summary> public static string Button_NoToAll { get { return ResourceManager.GetString("Button_NoToAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _OK. /// </summary> public static string Button_OK { get { return ResourceManager.GetString("Button_OK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Preview. /// </summary> public static string Button_Preview { get { return ResourceManager.GetString("Button_Preview", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Restart search. /// </summary> public static string Button_RestartSearch { get { return ResourceManager.GetString("Button_RestartSearch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show errors in output. /// </summary> public static string Button_ShowErrors { get { return ResourceManager.GetString("Button_ShowErrors", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show {0} more results. /// </summary> public static string Button_ShowMoreResults { get { return ResourceManager.GetString("Button_ShowMoreResults", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uninstall. /// </summary> public static string Button_Uninstall { get { return ResourceManager.GetString("Button_Uninstall", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Update. /// </summary> public static string Button_Update { get { return ResourceManager.GetString("Button_Update", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Upgrade. /// </summary> public static string Button_Upgrade { get { return ResourceManager.GetString("Button_Upgrade", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Yes. /// </summary> public static string Button_Yes { get { return ResourceManager.GetString("Button_Yes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Yes to _All. /// </summary> public static string Button_YesToAll { get { return ResourceManager.GetString("Button_YesToAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Check. /// </summary> public static string CheckBox_DefaultAction_Check { get { return ResourceManager.GetString("CheckBox_DefaultAction_Check", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uncheck. /// </summary> public static string CheckBox_DefaultAction_Uncheck { get { return ResourceManager.GetString("CheckBox_DefaultAction_Uncheck", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Allow format selection on first package install. /// </summary> public static string CheckBox_DefaultPackageFormat { get { return ResourceManager.GetString("CheckBox_DefaultPackageFormat", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Force uninstall, even if there are dependencies on it. /// </summary> public static string Checkbox_ForceRemove { get { return ResourceManager.GetString("Checkbox_ForceRemove", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Include prerelease. /// </summary> public static string Checkbox_IncludePrerelease { get { return ResourceManager.GetString("Checkbox_IncludePrerelease", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} project(s). /// </summary> public static string Checkbox_ProjectSelection { get { return ResourceManager.GetString("Checkbox_ProjectSelection", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove dependencies. /// </summary> public static string Checkbox_RemoveDependencies { get { return ResourceManager.GetString("Checkbox_RemoveDependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select all packages. /// </summary> public static string Checkbox_SelectAllPackages { get { return ResourceManager.GetString("Checkbox_SelectAllPackages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select All Projects. /// </summary> public static string CheckBox_SelectAllProjects { get { return ResourceManager.GetString("CheckBox_SelectAllProjects", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select this checkbox to install the NuGet Package to all projects in the solution. /// </summary> public static string CheckBox_SelectAllProjects_HelpText { get { return ResourceManager.GetString("CheckBox_SelectAllProjects_HelpText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Selected. /// </summary> public static string CheckBox_Selected { get { return ResourceManager.GetString("CheckBox_Selected", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select this checkbox to install the NuGet Package to the project &apos;{0}&apos;. /// </summary> public static string CheckBox_SelectProject_HelpText { get { return ResourceManager.GetString("CheckBox_SelectProject_HelpText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show preview window. /// </summary> public static string Checkbox_ShowPreviewWindow { get { return ResourceManager.GetString("Checkbox_ShowPreviewWindow", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installed. /// </summary> public static string ColumnHeader_InstalledVersion { get { return ResourceManager.GetString("ColumnHeader_InstalledVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project. /// </summary> public static string ColumnHeader_Project { get { return ResourceManager.GetString("ColumnHeader_Project", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version. /// </summary> public static string ColumnHeader_Requested { get { return ResourceManager.GetString("ColumnHeader_Requested", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Selected. /// </summary> public static string ColumnHeader_Selected { get { return ResourceManager.GetString("ColumnHeader_Selected", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Highest. /// </summary> public static string DependencyBehavior_Highest { get { return ResourceManager.GetString("DependencyBehavior_Highest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Highest Minor. /// </summary> public static string DependencyBehavior_HighestMinor { get { return ResourceManager.GetString("DependencyBehavior_HighestMinor", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Highest Patch. /// </summary> public static string DependencyBehavior_HighestPatch { get { return ResourceManager.GetString("DependencyBehavior_HighestPatch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ignore Dependencies. /// </summary> public static string DependencyBehavior_IgnoreDependencies { get { return ResourceManager.GetString("DependencyBehavior_IgnoreDependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Lowest. /// </summary> public static string DependencyBehavior_Lowest { get { return ResourceManager.GetString("DependencyBehavior_Lowest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select to view the alternative package.. /// </summary> public static string Deprecation_LinkTooltip { get { return ResourceManager.GetString("Deprecation_LinkTooltip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to More info. /// </summary> public static string Deprecation_MoreInfo { get { return ResourceManager.GetString("Deprecation_MoreInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package version is deprecated.. /// </summary> public static string Deprecation_PackageItemMessage { get { return ResourceManager.GetString("Deprecation_PackageItemMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package version is deprecated. Use {0} instead.. /// </summary> public static string Deprecation_PackageItemMessageAlternative { get { return ResourceManager.GetString("Deprecation_PackageItemMessageAlternative", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Learn more. /// </summary> public static string Description_LearnMore { get { return ResourceManager.GetString("Description_LearnMore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Do not show this again. /// </summary> public static string DoNotShowThisAgain { get { return ResourceManager.GetString("DoNotShowThisAgain", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No repository is selected. /// </summary> public static string Error_NoActiveRepository { get { return ResourceManager.GetString("Error_NoActiveRepository", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project {0} does not exist in the project system cache.. /// </summary> public static string Error_ProjectNotInCache { get { return ResourceManager.GetString("Error_ProjectNotInCache", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Operation failed. /// </summary> public static string ErrorDialogBoxTitle { get { return ResourceManager.GetString("ErrorDialogBoxTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ignore All. /// </summary> public static string FileConflictAction_IgnoreAll { get { return ResourceManager.GetString("FileConflictAction_IgnoreAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Overwrite All. /// </summary> public static string FileConflictAction_OverwriteAll { get { return ResourceManager.GetString("FileConflictAction_OverwriteAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prompt. /// </summary> public static string FileConflictAction_Prompt { get { return ResourceManager.GetString("FileConflictAction_Prompt", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Install and Update Options. /// </summary> public static string GroupBoxHeader_InstallOptions { get { return ResourceManager.GetString("GroupBoxHeader_InstallOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uninstall Options. /// </summary> public static string GroupBoxHeader_UninstallOptions { get { return ResourceManager.GetString("GroupBoxHeader_UninstallOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Advisory URL. /// </summary> public static string Hyperlink_AdvisoryUrl { get { return ResourceManager.GetString("Hyperlink_AdvisoryUrl", resourceCulture); } } /// <summary> /// Looks up a localized string similar to License. /// </summary> public static string Hyperlink_License { get { return ResourceManager.GetString("Hyperlink_License", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project URL. /// </summary> public static string Hyperlink_ProjectUrl { get { return ResourceManager.GetString("Hyperlink_ProjectUrl", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Readme. /// </summary> public static string Hyperlink_Readme { get { return ResourceManager.GetString("Hyperlink_Readme", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Report Abuse. /// </summary> public static string Hyperlink_ReportAbuse { get { return ResourceManager.GetString("Hyperlink_ReportAbuse", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ignore for now. /// </summary> public static string IgnoreUpgrade { get { return ResourceManager.GetString("IgnoreUpgrade", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Help icon. /// </summary> public static string ImageCaption_HelpIcon { get { return ResourceManager.GetString("ImageCaption_HelpIcon", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Action:. /// </summary> public static string Label_Action { get { return ResourceManager.GetString("Label_Action", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Author(s): . /// </summary> public static string Label_Authors { get { return ResourceManager.GetString("Label_Authors", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Browse. /// </summary> public static string Label_Browse { get { return ResourceManager.GetString("Label_Browse", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Date published:. /// </summary> public static string Label_DatePublished { get { return ResourceManager.GetString("Label_DatePublished", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Dependencies. /// </summary> public static string Label_Dependencies { get { return ResourceManager.GetString("Label_Dependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Dependency behavior:. /// </summary> public static string Label_DependencyBehavior { get { return ResourceManager.GetString("Label_DependencyBehavior", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Deprecated. /// </summary> public static string Label_Deprecated { get { return ResourceManager.GetString("Label_Deprecated", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Alternate package. /// </summary> public static string Label_DeprecationAlternatePackage { get { return ResourceManager.GetString("Label_DeprecationAlternatePackage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Deprecation reason. /// </summary> public static string Label_DeprecationReasons { get { return ResourceManager.GetString("Label_DeprecationReasons", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package has been deprecated as it has critical bugs.. /// </summary> public static string Label_DeprecationReasons_CriticalBugs { get { return ResourceManager.GetString("Label_DeprecationReasons_CriticalBugs", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package has been deprecated as it is legacy and no longer maintained.. /// </summary> public static string Label_DeprecationReasons_Legacy { get { return ResourceManager.GetString("Label_DeprecationReasons_Legacy", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package has been deprecated as it has critical bugs and is no longer maintained.. /// </summary> public static string Label_DeprecationReasons_LegacyAndCriticalBugs { get { return ResourceManager.GetString("Label_DeprecationReasons_LegacyAndCriticalBugs", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The package has been deprecated.. /// </summary> public static string Label_DeprecationReasons_Unknown { get { return ResourceManager.GetString("Label_DeprecationReasons_Unknown", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Description. /// </summary> public static string Label_Description { get { return ResourceManager.GetString("Label_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Details. /// </summary> public static string Label_Details { get { return ResourceManager.GetString("Label_Details", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Downloads:. /// </summary> public static string Label_Downloads { get { return ResourceManager.GetString("Label_Downloads", resourceCulture); } } /// <summary> /// Looks up a localized string similar to File conflict action:. /// </summary> public static string Label_FileConflictAction { get { return ResourceManager.GetString("Label_FileConflictAction", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Filter:. /// </summary> public static string Label_Filter { get { return ResourceManager.GetString("Label_Filter", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installed. /// </summary> public static string Label_Installed { get { return ResourceManager.GetString("Label_Installed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You have {0} deprecated package versions installed.. /// </summary> public static string Label_Installed_DeprecatedWarning { get { return ResourceManager.GetString("Label_Installed_DeprecatedWarning", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You have {0} vulnerable package versions and {1} deprecated package versions installed.. /// </summary> public static string Label_Installed_VulnerableAndDeprecatedWarning { get { return ResourceManager.GetString("Label_Installed_VulnerableAndDeprecatedWarning", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You have {0} vulnerable package versions installed.. /// </summary> public static string Label_Installed_VulnerableWarning { get { return ResourceManager.GetString("Label_Installed_VulnerableWarning", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installed:. /// </summary> public static string Label_InstalledColon { get { return ResourceManager.GetString("Label_InstalledColon", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installing:. /// </summary> public static string Label_InstalledPackages { get { return ResourceManager.GetString("Label_InstalledPackages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Versions - {0}. /// </summary> public static string Label_InstalledVersionsCount { get { return ResourceManager.GetString("Label_InstalledVersionsCount", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Legal Disclaimer. /// </summary> public static string Label_LegalDisclaimer { get { return ResourceManager.GetString("Label_LegalDisclaimer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to License:. /// </summary> public static string Label_License { get { return ResourceManager.GetString("Label_License", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet: {0}. /// </summary> public static string Label_NuGetWindowCaption { get { return ResourceManager.GetString("Label_NuGetWindowCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Options. /// </summary> public static string Label_Options { get { return ResourceManager.GetString("Label_Options", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Owner(s):. /// </summary> public static string Label_Owners { get { return ResourceManager.GetString("Label_Owners", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package version is deprecated.. /// </summary> public static string Label_PackageDeprecatedToolTip { get { return ResourceManager.GetString("Label_PackageDeprecatedToolTip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet Package Manager: {0}. /// </summary> public static string Label_PackageManager { get { return ResourceManager.GetString("Label_PackageManager", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prerelease. /// </summary> public static string Label_PackagePrerelease { get { return ResourceManager.GetString("Label_PackagePrerelease", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select to view package details for more information.. /// </summary> public static string Label_PackageSelectForInfoToolTip { get { return ResourceManager.GetString("Label_PackageSelectForInfoToolTip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package version has a vulnerability with {0} severity.. /// </summary> public static string Label_PackageVulnerableToolTip { get { return ResourceManager.GetString("Label_PackageVulnerableToolTip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select which projects to apply changes to:. /// </summary> public static string Label_Projects { get { return ResourceManager.GetString("Label_Projects", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project URL:. /// </summary> public static string Label_ProjectUrl { get { return ResourceManager.GetString("Label_ProjectUrl", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Publisher(s):. /// </summary> public static string Label_Publishers { get { return ResourceManager.GetString("Label_Publishers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Readme:. /// </summary> public static string Label_Readme { get { return ResourceManager.GetString("Label_Readme", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Report Abuse:. /// </summary> public static string Label_ReportAbuse { get { return ResourceManager.GetString("Label_ReportAbuse", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package source:. /// </summary> public static string Label_Repository { get { return ResourceManager.GetString("Label_Repository", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Solution &apos;{0}&apos;. /// </summary> public static string Label_Solution { get { return ResourceManager.GetString("Label_Solution", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet - Solution. /// </summary> public static string Label_SolutionNuGetWindowCaption { get { return ResourceManager.GetString("Label_SolutionNuGetWindowCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Manage Packages for Solution. /// </summary> public static string Label_SolutionPackageManager { get { return ResourceManager.GetString("Label_SolutionPackageManager", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Tags:. /// </summary> public static string Label_Tags { get { return ResourceManager.GetString("Label_Tags", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uninstalling:. /// </summary> public static string Label_UninstalledPackages { get { return ResourceManager.GetString("Label_UninstalledPackages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Updates:. /// </summary> public static string Label_UpdatedPackages { get { return ResourceManager.GetString("Label_UpdatedPackages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Updates. /// </summary> public static string Label_Updates { get { return ResourceManager.GetString("Label_Updates", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version:. /// </summary> public static string Label_Version { get { return ResourceManager.GetString("Label_Version", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Vulnerabilities detected ({0}). /// </summary> public static string Label_Vulnerabilities { get { return ResourceManager.GetString("Label_Vulnerabilities", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This package version has at least one vulnerability with {0} severity. It may lead to specific problems in your project. Try updating the package version.. /// </summary> public static string Label_VulnerabilitiesDescription { get { return ResourceManager.GetString("Label_VulnerabilitiesDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Advisory ({0} severity):. /// </summary> public static string Label_VulnerabilityAdvisory { get { return ResourceManager.GetString("Label_VulnerabilityAdvisory", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Loading license file.... /// </summary> public static string LicenseFile_Loading { get { return ResourceManager.GetString("LicenseFile_Loading", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} license. /// </summary> public static string LicenseTerm_LinkName { get { return ResourceManager.GetString("LicenseTerm_LinkName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Don&apos;t show again. /// </summary> public static string Link_DoNotShowAgain { get { return ResourceManager.GetString("Link_DoNotShowAgain", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Learn about Install Options. /// </summary> public static string Link_LearnAboutInstallOptions { get { return ResourceManager.GetString("Link_LearnAboutInstallOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Learn about Uninstall Options. /// </summary> public static string Link_LearnAboutUninstallOptions { get { return ResourceManager.GetString("Link_LearnAboutUninstallOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Why should I migrate?. /// </summary> public static string Link_MigratorHelp { get { return ResourceManager.GetString("Link_MigratorHelp", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Reverting NuGet Project Upgrade. /// </summary> public static string Link_RevertNuGetProjectUpgrade { get { return ResourceManager.GetString("Link_RevertNuGetProjectUpgrade", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Migrate Now. /// </summary> public static string Link_UpgradeOption { get { return ResourceManager.GetString("Link_UpgradeOption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package Id. /// </summary> public static string Migrator_PackageIdColumnHeader { get { return ResourceManager.GetString("Migrator_PackageIdColumnHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Migration failed as packages {0} could not be uninstalled. These packages were not found in the solution packages folder. No changes were made to the project.. /// </summary> public static string Migrator_PackageNotFound { get { return ResourceManager.GetString("Migrator_PackageNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Top-Level. /// </summary> public static string Migrator_TopLevelColumnHeader { get { return ResourceManager.GetString("Migrator_TopLevelColumnHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version. /// </summary> public static string Migrator_VersionColumnHeader { get { return ResourceManager.GetString("Migrator_VersionColumnHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0:G3}M. /// </summary> public static string Million { get { return ResourceManager.GetString("Million", resourceCulture); } } /// <summary> /// Looks up a localized string similar to (dependency of {0}). /// </summary> public static string NuGetUpgrade_PackageDependencyOf { get { return ResourceManager.GetString("NuGetUpgrade_PackageDependencyOf", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installing required packages. /// </summary> public static string NuGetUpgrade_Progress_Installing { get { return ResourceManager.GetString("NuGetUpgrade_Progress_Installing", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uninstalling packages from packages.config. /// </summary> public static string NuGetUpgrade_Progress_Uninstalling { get { return ResourceManager.GetString("NuGetUpgrade_Progress_Uninstalling", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Upgrading Project to PackageReference. /// </summary> public static string NuGetUpgrade_WaitMessage { get { return ResourceManager.GetString("NuGetUpgrade_WaitMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Time Elapsed: {0}. /// </summary> public static string Operation_TotalTime { get { return ResourceManager.GetString("Operation_TotalTime", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Top-level packages. /// </summary> public static string PackageLevel_TopLevelPackageHeaderText { get { return ResourceManager.GetString("PackageLevel_TopLevelPackageHeaderText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transitive packages. /// </summary> public static string PackageLevel_TransitivePackageHeaderText { get { return ResourceManager.GetString("PackageLevel_TransitivePackageHeaderText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Finished configuring this solution to restore NuGet packages on build.. /// </summary> public static string PackageRestoreCompleted { get { return ResourceManager.GetString("PackageRestoreCompleted", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Do you want to configure this solution to download and restore missing NuGet packages during build? A .nuget folder will be added to the root of the solution that contains files that enable package restore. /// ///Packages installed into Website projects will not be restored during build. Consider converting those into Web application projects if necessary.. /// </summary> public static string PackageRestoreConfirmation { get { return ResourceManager.GetString("PackageRestoreConfirmation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Downloading package &apos;{0}&apos; failed.. /// </summary> public static string PackageRestoreDownloadPackageFailed { get { return ResourceManager.GetString("PackageRestoreDownloadPackageFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An error occurred while configuring the solution to restore NuGet packages on build. /// </summary> public static string PackageRestoreErrorMessage { get { return ResourceManager.GetString("PackageRestoreErrorMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An error occurred while trying to restore packages:. /// </summary> public static string PackageRestoreErrorTryAgain { get { return ResourceManager.GetString("PackageRestoreErrorTryAgain", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Downloading missing packages.... /// </summary> public static string PackageRestoreProgressMessage { get { return ResourceManager.GetString("PackageRestoreProgressMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Configuring the solution to restore NuGet packages on build.... /// </summary> public static string PackageRestoreWaitMessage { get { return ResourceManager.GetString("PackageRestoreWaitMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Getting Package Sources.... /// </summary> public static string PackageSourceOptions_OnActivated { get { return ResourceManager.GetString("PackageSourceOptions_OnActivated", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Applying changes.... /// </summary> public static string PackageSourceOptions_OnApply { get { return ResourceManager.GetString("PackageSourceOptions_OnApply", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} by {1}. /// </summary> public static string PackageVersionWithTransitiveOrigins { get { return ResourceManager.GetString("PackageVersionWithTransitiveOrigins", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} version {1} to {2} version {3}. /// </summary> public static string Preview_PackageUpdate { get { return ResourceManager.GetString("Preview_PackageUpdate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unknown project. /// </summary> public static string Preview_UnknownProject { get { return ResourceManager.GetString("Preview_UnknownProject", resourceCulture); } } /// <summary> /// Looks up a localized string similar to PackageReference in project file. /// </summary> public static string RadioBtn_PackageRef { get { return ResourceManager.GetString("RadioBtn_PackageRef", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Packages.config. /// </summary> public static string RadioBtn_PackagesConfig { get { return ResourceManager.GetString("RadioBtn_PackagesConfig", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Refresh. /// </summary> public static string RefreshButtonLabel { get { return ResourceManager.GetString("RefreshButtonLabel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Multiple packages failed to uninstall. Restart Visual Studio to finish the process.. /// </summary> public static string RequestRestartToCompleteUninstallMultiplePackages { get { return ResourceManager.GetString("RequestRestartToCompleteUninstallMultiplePackages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The package at &apos;{0}&apos; failed to uninstall. Restart Visual Studio to finish the process.. /// </summary> public static string RequestRestartToCompleteUninstallSinglePackage { get { return ResourceManager.GetString("RequestRestartToCompleteUninstallSinglePackage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rest_art. /// </summary> public static string RestartButtonLabel { get { return ResourceManager.GetString("RestartButtonLabel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Restore. /// </summary> public static string RestoreButtonLabel { get { return ResourceManager.GetString("RestoreButtonLabel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show Details. /// </summary> public static string ShowDetails { get { return ResourceManager.GetString("ShowDetails", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed to apply NuGet Package Manager settings. Please report a problem using Help &gt; Send Feedback &gt; Report a Problem.. /// </summary> public static string ShowError_ApplySettingFailed { get { return ResourceManager.GetString("ShowError_ApplySettingFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Can not access NuGet.Config, Please check NuGet.Config. /// </summary> public static string ShowError_ConfigUnauthorizedAccess { get { return ResourceManager.GetString("ShowError_ConfigUnauthorizedAccess", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed to initialize NuGet Package Manager Settings. Please report a problem using Help &gt; Send Feedback &gt; Report a Problem.. /// </summary> public static string ShowError_SettingActivatedFailed { get { return ResourceManager.GetString("ShowError_SettingActivatedFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to All packages have been cleared from the cache.. /// </summary> public static string ShowInfo_ClearPackageCache { get { return ResourceManager.GetString("ShowInfo_ClearPackageCache", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet cache(s) clear failed at {0}. ///Error: {1} ///Please see https://aka.ms/troubleshoot_nuget_cache for more help.. /// </summary> public static string ShowMessage_LocalsCommandFailure { get { return ResourceManager.GetString("ShowMessage_LocalsCommandFailure", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet cache(s) cleared at {0}. /// </summary> public static string ShowMessage_LocalsCommandSuccess { get { return ResourceManager.GetString("ShowMessage_LocalsCommandSuccess", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Clearing all NuGet cache(s). . /// </summary> public static string ShowMessage_LocalsCommandWorking { get { return ResourceManager.GetString("ShowMessage_LocalsCommandWorking", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The source specified is invalid. Please provide a valid source.. /// </summary> public static string ShowWarning_InvalidSource { get { return ResourceManager.GetString("ShowWarning_InvalidSource", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The name and source specified cannot be empty. Please provide a valid name and source.. /// </summary> public static string ShowWarning_NameAndSourceRequired { get { return ResourceManager.GetString("ShowWarning_NameAndSourceRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The name specified cannot be empty. Please provide a valid name.. /// </summary> public static string ShowWarning_NameRequired { get { return ResourceManager.GetString("ShowWarning_NameRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified source&apos;s name is an official package source name, but there is already an official package source. Please provide a different name.. /// </summary> public static string ShowWarning_OfficialSourceName { get { return ResourceManager.GetString("ShowWarning_OfficialSourceName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The source specified cannot be empty. Please provide a valid source.. /// </summary> public static string ShowWarning_SourceRequried { get { return ResourceManager.GetString("ShowWarning_SourceRequried", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package Manager Options. /// </summary> public static string ShowWarning_Title { get { return ResourceManager.GetString("ShowWarning_Title", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The name specified has already been added to the list of available package sources. Please provide a unique name.. /// </summary> public static string ShowWarning_UniqueName { get { return ResourceManager.GetString("ShowWarning_UniqueName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The source specified has already been added to the list of available package sources. Please provide a unique source.. /// </summary> public static string ShowWarning_UniqueSource { get { return ResourceManager.GetString("ShowWarning_UniqueSource", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Canceled loading packages. /// </summary> public static string Status_Canceled { get { return ResourceManager.GetString("Status_Canceled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An error occurred while loading packages. /// </summary> public static string Status_ErrorOccurred { get { return ResourceManager.GetString("Status_ErrorOccurred", resourceCulture); } } /// <summary> /// Looks up a localized string similar to End of package list loaded. /// </summary> public static string Status_NoMoreItems { get { return ResourceManager.GetString("Status_NoMoreItems", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package list loaded. /// </summary> public static string Status_Ready { get { return ResourceManager.GetString("Status_Ready", resourceCulture); } } /// <summary> /// Looks up a localized string similar to by {0}. /// </summary> public static string Text_ByAuthor { get { return ResourceManager.GetString("Text_ByAuthor", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Visual Studio is about to make changes to this solution. Click OK to proceed with the changes listed below.. /// </summary> public static string Text_Changes { get { return ResourceManager.GetString("Text_Changes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Changes for {0}. /// </summary> public static string Text_ChangesForProject { get { return ResourceManager.GetString("Text_ChangesForProject", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Top-level dependencies:. /// </summary> public static string Text_DirectDependencies { get { return ResourceManager.GetString("Text_DirectDependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} downloads. /// </summary> public static string Text_Downloads { get { return ResourceManager.GetString("Text_Downloads", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error details. /// </summary> public static string Text_ErrorDetails { get { return ResourceManager.GetString("Text_ErrorDetails", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error occurred. /// </summary> public static string Text_ErrorOccurred { get { return ResourceManager.GetString("Text_ErrorOccurred", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Help me migrate to NuGet PackageReference. /// </summary> public static string Text_HelpMeMigrate { get { return ResourceManager.GetString("Text_HelpMeMigrate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installed version: {0}. /// </summary> public static string Text_InstalledVersion { get { return ResourceManager.GetString("Text_InstalledVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Each package is licensed to you by its owner. NuGet is not responsible for, nor does it grant any licenses to, third-party packages.. /// </summary> public static string Text_LegalDisclaimer { get { return ResourceManager.GetString("Text_LegalDisclaimer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to License Acceptance. /// </summary> public static string Text_LicenseAcceptance { get { return ResourceManager.GetString("Text_LicenseAcceptance", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The following package(s) require that you accept their license terms before installing.. /// </summary> public static string Text_LicenseHeaderText { get { return ResourceManager.GetString("Text_LicenseHeaderText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to By clicking &quot;I Accept,&quot; you agree to the license terms for the package(s) listed above. If you do not agree to the license terms, click &quot;I Decline.&quot;. /// </summary> public static string Text_LicenseText { get { return ResourceManager.GetString("Text_LicenseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Loading.... /// </summary> public static string Text_Loading { get { return ResourceManager.GetString("Text_Loading", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You can manage these settings in . /// </summary> public static string Text_ManageSettings { get { return ResourceManager.GetString("Text_ManageSettings", resourceCulture); } } /// <summary> /// Looks up a localized string similar to multiple versions installed. /// </summary> public static string Text_MultipleVersionsInstalled { get { return ResourceManager.GetString("Text_MultipleVersionsInstalled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No dependencies. /// </summary> public static string Text_NoDependencies { get { return ResourceManager.GetString("Text_NoDependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No more packages. /// </summary> public static string Text_NoMorePackages { get { return ResourceManager.GetString("Text_NoMorePackages", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No packages found. /// </summary> public static string Text_NoPackagesFound { get { return ResourceManager.GetString("Text_NoPackagesFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Not available in this source. /// </summary> public static string Text_NotAvailableInSource { get { return ResourceManager.GetString("Text_NotAvailableInSource", resourceCulture); } } /// <summary> /// Looks up a localized string similar to not installed. /// </summary> public static string Text_NotInstalled { get { return ResourceManager.GetString("Text_NotInstalled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet Settings. /// </summary> public static string Text_NuGetSettings { get { return ResourceManager.GetString("Text_NuGetSettings", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package compatibility issues:. /// </summary> public static string Text_NuGetUpgradeIssues { get { return ResourceManager.GetString("Text_NuGetUpgradeIssues", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No issues were found.. /// </summary> public static string Text_NuGetUpgradeNoIssuesFound { get { return ResourceManager.GetString("Text_NuGetUpgradeNoIssuesFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You must resolve any errors before upgrading.. /// </summary> public static string Text_NuGetUpgradeResolveErrorsBeforeUpgrading { get { return ResourceManager.GetString("Text_NuGetUpgradeResolveErrorsBeforeUpgrading", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The package manager format will apply to the following projects in this Solution. /// </summary> public static string Text_PackageFormatApply { get { return ResourceManager.GetString("Text_PackageFormatApply", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Projects with PackageReference are not supported in Visual Studio 2015 and earlier.. /// </summary> public static string Text_PackageRefSupport { get { return ResourceManager.GetString("Text_PackageRefSupport", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Learn more about package reference. /// </summary> public static string Text_PackageRefSupport_DocumentLink { get { return ResourceManager.GetString("Text_PackageRefSupport_DocumentLink", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Packages found. /// </summary> public static string Text_PackagesFound { get { return ResourceManager.GetString("Text_PackagesFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Package sources:. /// </summary> public static string Text_PackageSources { get { return ResourceManager.GetString("Text_PackageSources", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Progress. /// </summary> public static string Text_Progress { get { return ResourceManager.GetString("Text_Progress", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project Analysis Results. /// </summary> public static string Text_ProjectAnalysisResults { get { return ResourceManager.GetString("Text_ProjectAnalysisResults", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ready. /// </summary> public static string Text_Ready { get { return ResourceManager.GetString("Text_Ready", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search ({0}). /// </summary> public static string Text_SearchBoxText { get { return ResourceManager.GetString("Text_SearchBoxText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search completed. /// </summary> public static string Text_SearchCompleted { get { return ResourceManager.GetString("Text_SearchCompleted", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Retrieving results from one or more sources. /// </summary> public static string Text_SearchIncomplete { get { return ResourceManager.GetString("Text_SearchIncomplete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Searching &apos;{0}&apos;. /// </summary> public static string Text_Searching { get { return ResourceManager.GetString("Text_Searching", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to retrieve results from one or more sources. /// </summary> public static string Text_SearchStopped { get { return ResourceManager.GetString("Text_SearchStopped", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show all. /// </summary> public static string Text_ShowAll { get { return ResourceManager.GetString("Text_ShowAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transitive dependencies:. /// </summary> public static string Text_TransitiveDependencies { get { return ResourceManager.GetString("Text_TransitiveDependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Upgrade Complete. /// </summary> public static string Text_UpgradeComplete { get { return ResourceManager.GetString("Text_UpgradeComplete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please build and run your solution to verify that all packages are available.. /// </summary> public static string Text_UpgradeCompletePleaseBuild { get { return ResourceManager.GetString("Text_UpgradeCompletePleaseBuild", resourceCulture); } } /// <summary> /// Looks up a localized string similar to If you run into any issues and would like to revert, we have backed up changed files to the following location:. /// </summary> public static string Text_UpgradeCompleteResolveProblemsBackup { get { return ResourceManager.GetString("Text_UpgradeCompleteResolveProblemsBackup", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Follow the directions described in the following document to revert changes:. /// </summary> public static string Text_UpgradeCompleteResolveProblemsDirections { get { return ResourceManager.GetString("Text_UpgradeCompleteResolveProblemsDirections", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Migrate this project from packages.config to PackageReference format.. /// </summary> public static string Text_UpgradeNuGetProjectDescription { get { return ResourceManager.GetString("Text_UpgradeNuGetProjectDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Packages as PackageReference:. /// </summary> public static string Text_UpgraderHeader { get { return ResourceManager.GetString("Text_UpgraderHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Operation canceled by user. /// </summary> public static string Text_UserCanceled { get { return ResourceManager.GetString("Text_UserCanceled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to View License. /// </summary> public static string Text_ViewLicense { get { return ResourceManager.GetString("Text_ViewLicense", resourceCulture); } } /// <summary> /// Looks up a localized string similar to View Readme. /// </summary> public static string Text_ViewReadme { get { return ResourceManager.GetString("Text_ViewReadme", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Working.... /// </summary> public static string Text_Working { get { return ResourceManager.GetString("Text_Working", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0:G3}K. /// </summary> public static string Thousand { get { return ResourceManager.GetString("Thousand", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Following versions are unavailable due to additional constraints in the project or packages.config. /// </summary> public static string ToolTip_BlockedVersion { get { return ResourceManager.GetString("ToolTip_BlockedVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Install {0} version {1}.. /// </summary> public static string ToolTip_InstallButton { get { return ResourceManager.GetString("ToolTip_InstallButton", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installed version: {0}. /// </summary> public static string ToolTip_InstalledVersion { get { return ResourceManager.GetString("ToolTip_InstalledVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Latest version: {0}. /// </summary> public static string ToolTip_LatestVersion { get { return ResourceManager.GetString("ToolTip_LatestVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Latest stable version is installed. /// </summary> public static string ToolTip_PackageInstalled { get { return ResourceManager.GetString("ToolTip_PackageInstalled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to IntelliCode package suggestion based on this project context. /// </summary> public static string ToolTip_PackageRecommended { get { return ResourceManager.GetString("ToolTip_PackageRecommended", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The ID prefix of this package has been reserved for the owner of the package by the currently selected feed. /// </summary> public static string Tooltip_PrefixReserved { get { return ResourceManager.GetString("Tooltip_PrefixReserved", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Refresh. /// </summary> public static string ToolTip_Refresh { get { return ResourceManager.GetString("ToolTip_Refresh", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Settings. /// </summary> public static string ToolTip_Settings { get { return ResourceManager.GetString("ToolTip_Settings", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transitively referenced version. /// </summary> public static string ToolTip_TransitiveDependency { get { return ResourceManager.GetString("ToolTip_TransitiveDependency", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uninstall this package.. /// </summary> public static string ToolTip_UninstallButton { get { return ResourceManager.GetString("ToolTip_UninstallButton", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Update available. /// </summary> public static string ToolTip_UpdateAvailable { get { return ResourceManager.GetString("ToolTip_UpdateAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Update {0} to version {1}.. /// </summary> public static string ToolTip_UpdateButton { get { return ResourceManager.GetString("ToolTip_UpdateButton", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0:G3}T. /// </summary> public static string Trillion { get { return ResourceManager.GetString("Trillion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet migrate failed to install packages as PackageReference. Changed files are backed up at {0}. /// </summary> public static string Upgrade_InstallFailed { get { return ResourceManager.GetString("Upgrade_InstallFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please follow simple instructions from {0} to go back to previous state.. /// </summary> public static string Upgrade_RevertSteps { get { return ResourceManager.GetString("Upgrade_RevertSteps", resourceCulture); } } /// <summary> /// Looks up a localized string similar to NuGet upgrade failed to uninstall packages from packages.config so rolled back to previous state.. /// </summary> public static string Upgrade_UninstallFailed { get { return ResourceManager.GetString("Upgrade_UninstallFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Must be a valid path.. /// </summary> public static string UpgradeLogger_BackupPathMustBeValid { get { return ResourceManager.GetString("UpgradeLogger_BackupPathMustBeValid", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The project cannot be upgraded as backing up the project file and packages.config ran into an issue.. /// </summary> public static string Upgrader_BackupFailed { get { return ResourceManager.GetString("Upgrader_BackupFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to determine compatibility of package as {0}.nupkg was not found on disk. The project cannot be migrated.. /// </summary> public static string Upgrader_PackageNotFound { get { return ResourceManager.GetString("Upgrader_PackageNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Blocked by package.config. /// </summary> public static string Version_Blocked { get { return ResourceManager.GetString("Version_Blocked", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Blocked by project. /// </summary> public static string Version_Blocked_Generic { get { return ResourceManager.GetString("Version_Blocked_Generic", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Installed. /// </summary> public static string Version_Installed { get { return ResourceManager.GetString("Version_Installed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Latest prerelease. /// </summary> public static string Version_LatestPrerelease { get { return ResourceManager.GetString("Version_LatestPrerelease", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Latest stable. /// </summary> public static string Version_LatestStable { get { return ResourceManager.GetString("Version_LatestStable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to critical. /// </summary> public static string VulnerabilitySeverity_Critical { get { return ResourceManager.GetString("VulnerabilitySeverity_Critical", resourceCulture); } } /// <summary> /// Looks up a localized string similar to high. /// </summary> public static string VulnerabilitySeverity_High { get { return ResourceManager.GetString("VulnerabilitySeverity_High", resourceCulture); } } /// <summary> /// Looks up a localized string similar to low. /// </summary> public static string VulnerabilitySeverity_Low { get { return ResourceManager.GetString("VulnerabilitySeverity_Low", resourceCulture); } } /// <summary> /// Looks up a localized string similar to moderate. /// </summary> public static string VulnerabilitySeverity_Moderate { get { return ResourceManager.GetString("VulnerabilitySeverity_Moderate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to These options are not applicable to projects managing their dependencies through project.json or PackageReference. /// </summary> public static string Warning_ProjectJson { get { return ResourceManager.GetString("Warning_ProjectJson", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Convert. /// </summary> public static string WindowTitle_ConvertPackagesConfigIntro { get { return ResourceManager.GetString("WindowTitle_ConvertPackagesConfigIntro", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Deprecated Framework. /// </summary> public static string WindowTitle_DeprecatedFramework { get { return ResourceManager.GetString("WindowTitle_DeprecatedFramework", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error. /// </summary> public static string WindowTitle_Error { get { return ResourceManager.GetString("WindowTitle_Error", resourceCulture); } } /// <summary> /// Looks up a localized string similar to File Conflict. /// </summary> public static string WindowTitle_FileConflict { get { return ResourceManager.GetString("WindowTitle_FileConflict", resourceCulture); } } /// <summary> /// Looks up a localized string similar to License Acceptance. /// </summary> public static string WindowTitle_LicenseAcceptance { get { return ResourceManager.GetString("WindowTitle_LicenseAcceptance", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} License. /// </summary> public static string WindowTitle_LicenseFileWindow { get { return ResourceManager.GetString("WindowTitle_LicenseFileWindow", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Migrate NuGet format to PackageReference - {0}. /// </summary> public static string WindowTitle_NuGetMigrator { get { return ResourceManager.GetString("WindowTitle_NuGetMigrator", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Choose NuGet Package Manager Format. /// </summary> public static string WindowTitle_PackageFormatSelector { get { return ResourceManager.GetString("WindowTitle_PackageFormatSelector", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Preview Changes. /// </summary> public static string WindowTitle_PreviewChanges { get { return ResourceManager.GetString("WindowTitle_PreviewChanges", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Progress. /// </summary> public static string WindowTitle_Progress { get { return ResourceManager.GetString("WindowTitle_Progress", resourceCulture); } } } }
37.053075
259
0.558783
[ "Apache-2.0" ]
MarkKharitonov/NuGet.Client
src/NuGet.Clients/NuGet.PackageManagement.UI/Resources.Designer.cs
101,231
C#
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Authors: // Brian O'Keefe (zer0keefie@gmail.com) // using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using MonoTests.System.Collections.Specialized; using NUnit.Framework; namespace MonoTests.System.Collections.ObjectModel { [TestFixture] public class ReadOnlyObservableCollectionTest { [Test] public void ClassTest() { // Because the collection cannot change, check to make sure exceptions are thrown for modifications. List<char> initial = new List<char> (); initial.Add ('A'); initial.Add ('B'); initial.Add ('C'); ObservableCollection<char> collection = new ObservableCollection<char> (initial); ReadOnlyObservableCollection<char> readOnlyCollection = new ReadOnlyObservableCollection<char> (collection); // Test the events PropertyChangedEventHandler pceh = delegate (object sender, PropertyChangedEventArgs e) { Assert.Fail ("No properties should change."); }; NotifyCollectionChangedEventHandler ncceh = delegate (object sender, NotifyCollectionChangedEventArgs e) { Assert.Fail ("The collection should not change."); }; ((INotifyPropertyChanged)readOnlyCollection).PropertyChanged += pceh; ((INotifyCollectionChanged)readOnlyCollection).CollectionChanged += ncceh; // Done with the events. ((INotifyPropertyChanged)readOnlyCollection).PropertyChanged -= pceh; ((INotifyCollectionChanged)readOnlyCollection).CollectionChanged -= ncceh; Assert.AreEqual (3, readOnlyCollection.Count, "RO_1"); CollectionChangedEventValidators.AssertEquivalentLists (initial, readOnlyCollection, "RO_2"); // Modifying the underlying collection bool propChanged = false; pceh = delegate (object sender, PropertyChangedEventArgs e) { propChanged = true; }; ncceh = delegate (object sender, NotifyCollectionChangedEventArgs e) { CollectionChangedEventValidators.ValidateAddOperation (e, new char [] { 'I' }, 3, "RO_3"); }; ((INotifyPropertyChanged)readOnlyCollection).PropertyChanged += pceh; ((INotifyCollectionChanged)readOnlyCollection).CollectionChanged += ncceh; // In theory, this will cause the properties to change. collection.Add ('I'); Assert.IsTrue (propChanged, "RO_4"); } } }
36.397849
111
0.755391
[ "Apache-2.0" ]
121468615/mono
mcs/class/WindowsBase/Test/System.Collections.ObjectModel/ReadOnlyObservableCollectionTest.cs
3,387
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hedron { public class Scene { private static Dictionary<int, Entity> m_EntityCache = new Dictionary<int, Entity>(); public static Entity FindEntityByTag(string tag) { return null; } } }
18.6
93
0.658602
[ "Apache-2.0" ]
Gabriel-Baril/hedron
hedron-core-csharp/src/Scene.cs
374
C#
using FluentValidation; using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Text; namespace Infrastructure.Validation { public static class ValidationExtensions { public static IRuleBuilderInitial<T, string> IsColor<T>(this IRuleBuilder<T, string> ruleBuilder) { return ruleBuilder.Custom((data, context) => { try { int argb = Int32.Parse(data.Replace("#", ""), NumberStyles.HexNumber); Color clr = Color.FromArgb(argb); } catch { context.AddFailure("invalid rgb color"); } }); } } }
25.8
105
0.537468
[ "MIT" ]
BionStt/TodoMVC-DDD-CQRS-EventSourcing
src/Infrastructure/Validation/ValidationExtensions.cs
776
C#
using System.Data; using API.Interfaces; using Microsoft.Data.SqlClient; namespace API.Services; public class SqlService : ISqlService, IDisposable { private readonly IConfiguration _configuration; // private readonly ILogger _logger; private readonly SqlConnection _connection; private readonly List<SqlCommand> _commands; private SqlTransaction? _transaction; public SqlService(IConfiguration configuration) { _configuration = configuration; // _logger = logger; _connection = new SqlConnection(_configuration.GetConnectionString("Default")); _connection.Open(); _commands = new List<SqlCommand>(); _transaction = null; } public DataTable ExecuteSingle(string query, Dictionary<string, object> parameters) { DataTable table = new DataTable(); using (SqlCommand command = new SqlCommand()) { command.Connection = _connection; command.CommandType = CommandType.Text; command.CommandText = query; // add parameters foreach (var key in parameters.Keys) { command.Parameters.AddWithValue(key, parameters[key]); } SqlDataReader reader = command.ExecuteReader(); table.Load(reader); } return table; } public void AddQuery(string query, Dictionary<string, object> parameters) { SqlCommand command = new SqlCommand(); if (_transaction == null) { _transaction = _connection.BeginTransaction("mainTransaction"); } command.Connection = _connection; command.Transaction = _transaction; command.CommandText = query; // add parameters foreach (var key in parameters.Keys) { command.Parameters.AddWithValue(key, parameters[key]); } // do not execute. Save to list for later _commands.Add(command); } public void SaveChanges() { try { foreach (var command in _commands) { command.ExecuteNonQuery(); } if (_transaction != null) { _transaction.Commit(); } } catch (Exception) { // _logger.LogError(ex, "unable to complete transaction. Rolling back"); if (_transaction != null) { try { _transaction.Rollback(); } catch (Exception) { // _logger.LogError(ex2, "Unable to rollback transaction. Has the connection closed?"); } } } } public void CancelChanges() { if (_transaction == null) return; try { _transaction.Rollback(); } catch (Exception) { // _logger.LogError(ex2, "Unable to rollback transaction. Has the connection closed?"); } } public void Dispose() { _connection.Dispose(); } }
27.206897
107
0.553549
[ "MIT" ]
justinloveless/paylocity-coding-challenge
PCC/API/Services/SqlService.cs
3,156
C#
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System.Text; using UnityEngine.EventSystems; namespace XCharts { public partial class CoordinateChart : BaseChart { private static readonly string s_DefaultAxisY = "axis_y"; private static readonly string s_DefaultAxisX = "axis_x"; private static readonly string s_DefaultDataZoom = "datazoom"; [SerializeField] protected Grid m_Grid = Grid.defaultGrid; [SerializeField] protected List<XAxis> m_XAxises = new List<XAxis>(); [SerializeField] protected List<YAxis> m_YAxises = new List<YAxis>(); [SerializeField] protected DataZoom m_DataZoom = DataZoom.defaultDataZoom; private bool m_DataZoomDrag; private bool m_DataZoomCoordinateDrag; private bool m_DataZoomStartDrag; private bool m_DataZoomEndDrag; private float m_DataZoomLastStartIndex; private float m_DataZoomLastEndIndex; private bool m_XAxisChanged; private bool m_YAxisChanged; private bool m_CheckMinMaxValue; private bool m_CheckDataZoomLabel; private List<XAxis> m_CheckXAxises = new List<XAxis>(); private List<YAxis> m_CheckYAxises = new List<YAxis>(); private Grid m_CheckCoordinate = Grid.defaultGrid; private Dictionary<int, List<Serie>> m_StackSeries = new Dictionary<int, List<Serie>>(); private List<float> m_SeriesCurrHig = new List<float>(); protected override void Awake() { base.Awake(); m_CheckMinMaxValue = false; InitDefaultAxises(); CheckMinMaxValue(); InitDataZoom(); InitAxisX(); InitAxisY(); m_Tooltip.UpdateToTop(); } protected override void Update() { base.Update(); CheckYAxis(); CheckXAxis(); CheckMinMaxValue(); CheckCoordinate(); CheckDataZoom(); } #if UNITY_EDITOR protected override void Reset() { base.Reset(); m_Grid = Grid.defaultGrid; m_XAxises.Clear(); m_YAxises.Clear(); Awake(); } #endif protected override void DrawChart(VertexHelper vh) { base.DrawChart(vh); DrawCoordinate(vh); DrawSerie(vh); DrawDataZoomSlider(vh); } protected virtual void DrawSerie(VertexHelper vh) { base.DrawChart(vh); if (!m_CheckMinMaxValue) return; bool yCategory = m_YAxises[0].IsCategory() || m_YAxises[1].IsCategory(); m_Series.GetStackSeries(ref m_StackSeries); int seriesCount = m_StackSeries.Count; m_BarLastOffset = 0; for (int j = 0; j < seriesCount; j++) { var serieList = m_StackSeries[j]; m_SeriesCurrHig.Clear(); for (int n = 0; n < serieList.Count; n++) { Serie serie = serieList[n]; serie.dataPoints.Clear(); var colorIndex = m_LegendRealShowName.IndexOf(serie.legendName); switch (serie.type) { case SerieType.Line: if (yCategory) DrawYLineSerie(vh, serie, colorIndex, ref m_SeriesCurrHig); else DrawXLineSerie(vh, serie, colorIndex, ref m_SeriesCurrHig); break; case SerieType.Bar: if (yCategory) DrawYBarSerie(vh, serie, colorIndex, ref m_SeriesCurrHig); else DrawXBarSerie(vh, serie, colorIndex, ref m_SeriesCurrHig); break; case SerieType.Scatter: case SerieType.EffectScatter: DrawScatterSerie(vh, colorIndex, serie); if (vh.currentVertCount > 60000) { m_Large++; RefreshChart(); return; } break; } } } DrawLabelBackground(vh); DrawLinePoint(vh); DrawLineArrow(vh); if (yCategory) DrawYTooltipIndicator(vh); else DrawXTooltipIndicator(vh); } protected override void CheckTootipArea(Vector2 local) { if (!IsInCooridate(local)) { m_Tooltip.ClearValue(); RefreshTooltip(); } else { var isCartesian = IsValue(); for (int i = 0; i < m_XAxises.Count; i++) { var xAxis = m_XAxises[i]; var yAxis = m_YAxises[i]; if (!xAxis.show && !yAxis.show) continue; if (isCartesian && xAxis.show && yAxis.show) { var yRate = (yAxis.maxValue - yAxis.minValue) / coordinateHig; var xRate = (xAxis.maxValue - xAxis.minValue) / coordinateWid; var yValue = yRate * (local.y - coordinateY - yAxis.zeroYOffset); if (yAxis.minValue > 0) yValue += yAxis.minValue; m_Tooltip.yValues[i] = yValue; var xValue = xRate * (local.x - coordinateX - xAxis.zeroXOffset); if (xAxis.minValue > 0) xValue += xAxis.minValue; m_Tooltip.xValues[i] = xValue; for (int j = 0; j < m_Series.Count; j++) { var serie = m_Series.GetSerie(j); for (int n = 0; n < serie.data.Count; n++) { var serieData = serie.data[n]; var xdata = serieData.data[0]; var ydata = serieData.data[1]; var symbolSize = serie.symbol.GetSize(serieData == null ? null : serieData.data); if (Mathf.Abs(xValue - xdata) / xRate < symbolSize && Mathf.Abs(yValue - ydata) / yRate < symbolSize) { m_Tooltip.dataIndex[i] = n; serieData.highlighted = true; } else { serieData.highlighted = false; } } } } else if (xAxis.IsCategory()) { var value = (yAxis.maxValue - yAxis.minValue) * (local.y - coordinateY - yAxis.zeroYOffset) / coordinateHig; if (yAxis.minValue > 0) value += yAxis.minValue; m_Tooltip.yValues[i] = value; for (int j = 0; j < xAxis.GetDataNumber(m_DataZoom); j++) { float splitWid = xAxis.GetDataWidth(coordinateWid, m_DataZoom); float pX = coordinateX + j * splitWid; if ((xAxis.boundaryGap && (local.x > pX && local.x <= pX + splitWid)) || (!xAxis.boundaryGap && (local.x > pX - splitWid / 2 && local.x <= pX + splitWid / 2))) { m_Tooltip.xValues[i] = j; m_Tooltip.dataIndex[i] = j; break; } } } else if (yAxis.IsCategory()) { var value = (xAxis.maxValue - xAxis.minValue) * (local.x - coordinateX - xAxis.zeroXOffset) / coordinateWid; if (xAxis.minValue > 0) value += xAxis.minValue; m_Tooltip.xValues[i] = value; for (int j = 0; j < yAxis.GetDataNumber(m_DataZoom); j++) { float splitWid = yAxis.GetDataWidth(coordinateHig, m_DataZoom); float pY = coordinateY + j * splitWid; if ((yAxis.boundaryGap && (local.y > pY && local.y <= pY + splitWid)) || (!yAxis.boundaryGap && (local.y > pY - splitWid / 2 && local.y <= pY + splitWid / 2))) { m_Tooltip.yValues[i] = j; m_Tooltip.dataIndex[i] = j; break; } } } } } if (m_Tooltip.IsSelected()) { m_Tooltip.UpdateContentPos(new Vector2(local.x + 18, local.y - 25)); RefreshTooltip(); if (m_Tooltip.IsDataIndexChanged() || m_Tooltip.type == Tooltip.Type.Corss) { m_Tooltip.UpdateLastDataIndex(); RefreshChart(); } } else if (m_Tooltip.IsActive()) { m_Tooltip.SetActive(false); RefreshChart(); } } private StringBuilder sb = new StringBuilder(100); protected override void RefreshTooltip() { base.RefreshTooltip(); int index; Axis tempAxis; bool isCartesian = IsValue(); if (isCartesian) { index = m_Tooltip.dataIndex[0]; tempAxis = m_XAxises[0]; } else if (m_XAxises[0].type == Axis.AxisType.Value) { index = (int)m_Tooltip.yValues[0]; tempAxis = m_YAxises[0]; } else { index = (int)m_Tooltip.xValues[0]; tempAxis = m_XAxises[0]; } if (index < 0) { if (m_Tooltip.IsActive()) { m_Tooltip.SetActive(false); RefreshChart(); } return; } if (string.IsNullOrEmpty(tooltip.formatter)) { sb.Length = 0; if (!isCartesian) { sb.Append(tempAxis.GetData(index, m_DataZoom)); } for (int i = 0; i < m_Series.Count; i++) { var serie = m_Series.GetSerie(i); if (serie.show) { string key = serie.name; float xValue, yValue; serie.GetXYData(index, m_DataZoom, out xValue, out yValue); if (isCartesian) { var serieData = serie.GetSerieData(index, m_DataZoom); if (serieData != null && serieData.highlighted) { sb.Append(key).Append(!string.IsNullOrEmpty(key) ? " : " : ""); sb.Append("[").Append(ChartCached.FloatToStr(xValue)).Append(",") .Append(ChartCached.FloatToStr(yValue)).Append("]\n"); } } else { sb.Append("\n") .Append("<color=#").Append(m_ThemeInfo.GetColorStr(i)).Append(">● </color>") .Append(key).Append(!string.IsNullOrEmpty(key) ? " : " : "") .Append(ChartCached.FloatToStr(yValue)); } } } m_Tooltip.UpdateContentText(sb.ToString().Trim()); } else { var category = tempAxis.GetData(index, m_DataZoom); m_Tooltip.UpdateContentText(m_Tooltip.GetFormatterContent(index, m_Series, category, m_DataZoom)); } var pos = m_Tooltip.GetContentPos(); if (pos.x + m_Tooltip.width > chartWidth) { pos.x = chartWidth - m_Tooltip.width; } if (pos.y - m_Tooltip.height < 0) { pos.y = m_Tooltip.height; } m_Tooltip.UpdateContentPos(pos); m_Tooltip.SetActive(true); for (int i = 0; i < m_XAxises.Count; i++) { UpdateAxisTooltipLabel(i, m_XAxises[i]); } for (int i = 0; i < m_YAxises.Count; i++) { UpdateAxisTooltipLabel(i, m_YAxises[i]); } } private void UpdateAxisTooltipLabel(int axisIndex, Axis axis) { var showTooltipLabel = axis.show && m_Tooltip.type == Tooltip.Type.Corss; axis.SetTooltipLabelActive(showTooltipLabel); if (!showTooltipLabel) return; string labelText = ""; Vector2 labelPos = Vector2.zero; if (axis is XAxis) { var posY = axisIndex > 0 ? coordinateY + coordinateHig : coordinateY; var diff = axisIndex > 0 ? -axis.axisLabel.fontSize - axis.axisLabel.margin - 3.5f : axis.axisLabel.margin / 2 + 1; if (axis.IsValue()) { labelText = ChartCached.FloatToStr(m_Tooltip.xValues[axisIndex], 2); labelPos = new Vector2(m_Tooltip.pointerPos.x, posY - diff); } else { labelText = axis.GetData((int)m_Tooltip.xValues[axisIndex], m_DataZoom); float splitWidth = axis.GetSplitWidth(coordinateWid, m_DataZoom); int index = (int)m_Tooltip.xValues[axisIndex]; float px = coordinateX + index * splitWidth + (axis.boundaryGap ? splitWidth / 2 : 0) + 0.5f; labelPos = new Vector2(px, posY - diff); } } else if (axis is YAxis) { var posX = axisIndex > 0 ? coordinateX + coordinateWid : coordinateX; var diff = axisIndex > 0 ? -axis.axisLabel.margin + 3 : axis.axisLabel.margin - 3; if (axis.IsValue()) { labelText = ChartCached.FloatToStr(m_Tooltip.yValues[axisIndex], 2); labelPos = new Vector2(posX - diff, m_Tooltip.pointerPos.y); } else { labelText = axis.GetData((int)m_Tooltip.yValues[axisIndex], m_DataZoom); float splitWidth = axis.GetSplitWidth(coordinateHig, m_DataZoom); int index = (int)m_Tooltip.yValues[axisIndex]; float py = coordinateY + index * splitWidth + (axis.boundaryGap ? splitWidth / 2 : 0); labelPos = new Vector2(posX - diff, py); } } axis.UpdateTooptipLabelText(labelText); axis.UpdateTooltipLabelPos(labelPos); } protected override void OnThemeChanged() { base.OnThemeChanged(); InitDataZoom(); InitAxisX(); InitAxisY(); } private void InitDefaultAxises() { if (m_XAxises.Count <= 0) { var axis1 = XAxis.defaultXAxis; var axis2 = XAxis.defaultXAxis; axis1.show = true; axis2.show = false; m_XAxises.Add(axis1); m_XAxises.Add(axis2); } if (m_YAxises.Count <= 0) { var axis1 = YAxis.defaultYAxis; var axis2 = YAxis.defaultYAxis; axis1.show = true; axis1.splitNumber = 5; axis1.boundaryGap = false; axis2.show = false; m_YAxises.Add(axis1); m_YAxises.Add(axis2); } foreach (var axis in m_XAxises) axis.minValue = axis.maxValue = 0; foreach (var axis in m_YAxises) axis.minValue = axis.maxValue = 0; } private void InitAxisY() { for (int i = 0; i < m_YAxises.Count; i++) { InitYAxis(i, m_YAxises[i]); } } private void InitYAxis(int yAxisIndex, YAxis yAxis) { yAxis.axisLabelTextList.Clear(); string objName = yAxisIndex > 0 ? s_DefaultAxisY + "2" : s_DefaultAxisY; var axisObj = ChartHelper.AddObject(objName, transform, chartAnchorMin, chartAnchorMax, chartPivot, new Vector2(chartWidth, chartHeight)); axisObj.transform.localPosition = Vector3.zero; axisObj.SetActive(yAxis.show && yAxis.axisLabel.show); ChartHelper.HideAllObject(axisObj); if (yAxis.IsValue() && yAxis.minValue == 0 && yAxis.maxValue == 0) return; var labelColor = yAxis.axisLabel.color == Color.clear ? (Color)m_ThemeInfo.axisTextColor : yAxis.axisLabel.color; int splitNumber = yAxis.GetSplitNumber(coordinateHig, m_DataZoom); float totalWidth = 0; for (int i = 0; i < splitNumber; i++) { Text txt; bool inside = yAxis.axisLabel.inside; if ((inside && yAxisIndex == 0) || (!inside && yAxisIndex == 1)) { txt = ChartHelper.AddTextObject(objName + i, axisObj.transform, m_ThemeInfo.font, labelColor, TextAnchor.MiddleLeft, Vector2.zero, Vector2.zero, new Vector2(0, 0.5f), new Vector2(m_Grid.left, 20), yAxis.axisLabel.fontSize, yAxis.axisLabel.rotate, yAxis.axisLabel.fontStyle); } else { txt = ChartHelper.AddTextObject(objName + i, axisObj.transform, m_ThemeInfo.font, labelColor, TextAnchor.MiddleRight, Vector2.zero, Vector2.zero, new Vector2(1, 0.5f), new Vector2(m_Grid.left, 20), yAxis.axisLabel.fontSize, yAxis.axisLabel.rotate, yAxis.axisLabel.fontStyle); } float labelWidth = yAxis.GetScaleWidth(coordinateHig, i, m_DataZoom); txt.transform.localPosition = GetLabelYPosition(totalWidth + (yAxis.boundaryGap ? labelWidth / 2 : 0), i, yAxisIndex, yAxis); txt.text = yAxis.GetLabelName(coordinateHig, i, yAxis.minValue, yAxis.maxValue, m_DataZoom); txt.gameObject.SetActive(yAxis.show && (yAxis.axisLabel.interval == 0 || i % (yAxis.axisLabel.interval + 1) == 0)); yAxis.axisLabelTextList.Add(txt); totalWidth += labelWidth; } if (yAxis.axisName.show) { var color = yAxis.axisName.color == Color.clear ? (Color)m_ThemeInfo.axisTextColor : yAxis.axisName.color; var fontSize = yAxis.axisName.fontSize; var offset = yAxis.axisName.offset; Text axisName = null; var zeroPos = new Vector3(coordinateX + m_XAxises[yAxisIndex].zeroXOffset, coordinateY); switch (yAxis.axisName.location) { case AxisName.Location.Start: axisName = ChartHelper.AddTextObject(objName + "_name", axisObj.transform, m_ThemeInfo.font, color, TextAnchor.MiddleCenter, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(100, 20), fontSize, yAxis.axisName.rotate, yAxis.axisName.fontStyle); axisName.transform.localPosition = yAxisIndex > 0 ? new Vector2(coordinateX + coordinateWid + offset.x, coordinateY - offset.y) : new Vector2(zeroPos.x + offset.x, coordinateY - offset.y); break; case AxisName.Location.Middle: axisName = ChartHelper.AddTextObject(objName + "_name", axisObj.transform, m_ThemeInfo.font, color, TextAnchor.MiddleRight, new Vector2(1, 0.5f), new Vector2(1, 0.5f), new Vector2(1, 0.5f), new Vector2(100, 20), fontSize, yAxis.axisName.rotate, yAxis.axisName.fontStyle); axisName.transform.localPosition = yAxisIndex > 0 ? new Vector2(coordinateX + coordinateWid - offset.x, coordinateY + coordinateHig / 2 + offset.y) : new Vector2(coordinateX - offset.x, coordinateY + coordinateHig / 2 + offset.y); break; case AxisName.Location.End: axisName = ChartHelper.AddTextObject(objName + "_name", axisObj.transform, m_ThemeInfo.font, color, TextAnchor.MiddleCenter, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(100, 20), fontSize, yAxis.axisName.rotate, yAxis.axisName.fontStyle); axisName.transform.localPosition = yAxisIndex > 0 ? new Vector2(coordinateX + coordinateWid + offset.x, coordinateY + coordinateHig + offset.y) : new Vector2(zeroPos.x + offset.x, coordinateY + coordinateHig + offset.y); break; } axisName.text = yAxis.axisName.name; } //init tooltip label if (m_Tooltip.gameObject) { Vector2 privot = yAxisIndex > 0 ? new Vector2(0, 0.5f) : new Vector2(1, 0.5f); var labelParent = m_Tooltip.gameObject.transform; GameObject labelObj = ChartHelper.AddTooltipLabel(objName + "_label", labelParent, m_ThemeInfo.font, privot); yAxis.SetTooltipLabel(labelObj); yAxis.SetTooltipLabelColor(m_ThemeInfo.tooltipBackgroundColor, m_ThemeInfo.tooltipTextColor); yAxis.SetTooltipLabelActive(yAxis.show && m_Tooltip.show && m_Tooltip.type == Tooltip.Type.Corss); } } private void InitAxisX() { for (int i = 0; i < m_XAxises.Count; i++) { InitXAxis(i, m_XAxises[i]); } } private void InitXAxis(int xAxisIndex, XAxis xAxis) { xAxis.axisLabelTextList.Clear(); string objName = xAxisIndex > 0 ? ChartHelper.Cancat(s_DefaultAxisX, 2) : s_DefaultAxisX; var axisObj = ChartHelper.AddObject(objName, transform, chartAnchorMin, chartAnchorMax, chartPivot, new Vector2(chartWidth, chartHeight)); axisObj.transform.localPosition = Vector3.zero; axisObj.SetActive(xAxis.show && xAxis.axisLabel.show); ChartHelper.HideAllObject(axisObj); if (xAxis.IsValue() && xAxis.minValue == 0 && xAxis.maxValue == 0) return; var labelColor = xAxis.axisLabel.color == Color.clear ? (Color)m_ThemeInfo.axisTextColor : xAxis.axisLabel.color; int splitNumber = xAxis.GetSplitNumber(coordinateWid, m_DataZoom); float totalWidth = 0; for (int i = 0; i < splitNumber; i++) { float labelWidth = xAxis.GetScaleWidth(coordinateWid, i, m_DataZoom); bool inside = xAxis.axisLabel.inside; Text txt = ChartHelper.AddTextObject(ChartHelper.Cancat(objName, i), axisObj.transform, m_ThemeInfo.font, labelColor, TextAnchor.MiddleCenter, new Vector2(0, 1), new Vector2(0, 1), new Vector2(1, 0.5f), new Vector2(labelWidth, 20), xAxis.axisLabel.fontSize, xAxis.axisLabel.rotate, xAxis.axisLabel.fontStyle); txt.transform.localPosition = GetLabelXPosition(totalWidth + (xAxis.boundaryGap ? labelWidth : labelWidth / 2), i, xAxisIndex, xAxis); totalWidth += labelWidth; txt.text = xAxis.GetLabelName(coordinateWid, i, xAxis.minValue, xAxis.maxValue, m_DataZoom); txt.gameObject.SetActive(xAxis.show && (xAxis.axisLabel.interval == 0 || i % (xAxis.axisLabel.interval + 1) == 0)); xAxis.axisLabelTextList.Add(txt); } if (xAxis.axisName.show) { var color = xAxis.axisName.color == Color.clear ? (Color)m_ThemeInfo.axisTextColor : xAxis.axisName.color; var fontSize = xAxis.axisName.fontSize; var offset = xAxis.axisName.offset; Text axisName = null; var zeroPos = new Vector3(coordinateX, coordinateY + m_YAxises[xAxisIndex].zeroYOffset); switch (xAxis.axisName.location) { case AxisName.Location.Start: axisName = ChartHelper.AddTextObject(ChartHelper.Cancat(objName, "_name"), axisObj.transform, m_ThemeInfo.font, color, TextAnchor.MiddleRight, new Vector2(1, 0.5f), new Vector2(1, 0.5f), new Vector2(1, 0.5f), new Vector2(100, 20), fontSize, xAxis.axisName.rotate, xAxis.axisName.fontStyle); axisName.transform.localPosition = xAxisIndex > 0 ? new Vector2(zeroPos.x - offset.x, coordinateY + coordinateHig + offset.y) : new Vector2(zeroPos.x - offset.x, zeroPos.y + offset.y); break; case AxisName.Location.Middle: axisName = ChartHelper.AddTextObject(ChartHelper.Cancat(objName, "_name"), axisObj.transform, m_ThemeInfo.font, color, TextAnchor.MiddleCenter, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(100, 20), fontSize, xAxis.axisName.rotate, xAxis.axisName.fontStyle); axisName.transform.localPosition = xAxisIndex > 0 ? new Vector2(coordinateX + coordinateWid / 2 + offset.x, coordinateY + coordinateHig - offset.y) : new Vector2(coordinateX + coordinateWid / 2 + offset.x, coordinateY - offset.y); break; case AxisName.Location.End: axisName = ChartHelper.AddTextObject(ChartHelper.Cancat(objName, "_name"), axisObj.transform, m_ThemeInfo.font, color, TextAnchor.MiddleLeft, new Vector2(0, 0.5f), new Vector2(0, 0.5f), new Vector2(0, 0.5f), new Vector2(100, 20), fontSize, xAxis.axisName.rotate, xAxis.axisName.fontStyle); axisName.transform.localPosition = xAxisIndex > 0 ? new Vector2(coordinateX + coordinateWid + offset.x, coordinateY + coordinateHig + offset.y) : new Vector2(coordinateX + coordinateWid + offset.x, zeroPos.y + offset.y); break; } axisName.text = xAxis.axisName.name; } if (m_Tooltip.gameObject) { Vector2 privot = xAxisIndex > 0 ? new Vector2(0.5f, 1) : new Vector2(0.5f, 1); var labelParent = m_Tooltip.gameObject.transform; GameObject labelObj = ChartHelper.AddTooltipLabel(ChartHelper.Cancat(objName, "_label"), labelParent, m_ThemeInfo.font, privot); xAxis.SetTooltipLabel(labelObj); xAxis.SetTooltipLabelColor(m_ThemeInfo.tooltipBackgroundColor, m_ThemeInfo.tooltipTextColor); xAxis.SetTooltipLabelActive(xAxis.show && m_Tooltip.show && m_Tooltip.type == Tooltip.Type.Corss); } } private void InitDataZoom() { var dataZoomObject = ChartHelper.AddObject(s_DefaultDataZoom, transform, chartAnchorMin, chartAnchorMax, chartPivot, new Vector2(chartWidth, chartHeight)); dataZoomObject.transform.localPosition = Vector3.zero; ChartHelper.HideAllObject(dataZoomObject); m_DataZoom.startLabel = ChartHelper.AddTextObject(s_DefaultDataZoom + "start", dataZoomObject.transform, m_ThemeInfo.font, m_ThemeInfo.dataZoomTextColor, TextAnchor.MiddleRight, Vector2.zero, Vector2.zero, new Vector2(1, 0.5f), new Vector2(200, 20), m_DataZoom.fontSize, 0, m_DataZoom.fontStyle); m_DataZoom.endLabel = ChartHelper.AddTextObject(s_DefaultDataZoom + "end", dataZoomObject.transform, m_ThemeInfo.font, m_ThemeInfo.dataZoomTextColor, TextAnchor.MiddleLeft, Vector2.zero, Vector2.zero, new Vector2(0, 0.5f), new Vector2(200, 20), m_DataZoom.fontSize, 0, m_DataZoom.fontStyle); m_DataZoom.SetLabelActive(false); raycastTarget = m_DataZoom.enable; var xAxis = m_XAxises[m_DataZoom.xAxisIndex]; if (xAxis != null) { xAxis.UpdateFilterData(m_DataZoom); } if (m_Series != null) { m_Series.UpdateFilterData(m_DataZoom); } } private Vector3 GetLabelYPosition(float scaleWid, int i, int yAxisIndex, YAxis yAxis) { var startX = yAxisIndex == 0 ? coordinateX : coordinateX + coordinateWid; var posX = 0f; var inside = yAxis.axisLabel.inside; if ((inside && yAxisIndex == 0) || (!inside && yAxisIndex == 1)) { posX = startX + yAxis.axisLabel.margin; } else { posX = startX - yAxis.axisLabel.margin; } return new Vector3(posX, coordinateY + scaleWid, 0); } private Vector3 GetLabelXPosition(float scaleWid, int i, int xAxisIndex, XAxis xAxis) { var startY = xAxisIndex == 0 ? coordinateY : coordinateY + coordinateHig; var posY = 0f; var inside = xAxis.axisLabel.inside; if ((inside && xAxisIndex == 0) || (!inside && xAxisIndex == 1)) { posY = startY + xAxis.axisLabel.margin + xAxis.axisLabel.fontSize / 2; } else { posY = startY - xAxis.axisLabel.margin - xAxis.axisLabel.fontSize / 2; } // if (xAxis.boundaryGap) // { // return new Vector3(coordinateX + (i + 1) * scaleWid, posY); // } // else // { // return new Vector3(coordinateX + (i + 1 - 0.5f) * scaleWid, posY); // } return new Vector3(coordinateX + scaleWid, posY); } private void CheckCoordinate() { if (m_CheckCoordinate != m_Grid) { m_CheckCoordinate.Copy(m_Grid); OnCoordinateChanged(); } } private void CheckYAxis() { if (m_YAxisChanged || !ChartHelper.IsValueEqualsList<YAxis>(m_CheckYAxises, m_YAxises)) { foreach (var axis in m_CheckYAxises) { YAxisPool.Release(axis); } m_CheckYAxises.Clear(); foreach (var axis in m_YAxises) m_CheckYAxises.Add(axis.Clone()); m_YAxisChanged = false; OnYAxisChanged(); } } private void CheckXAxis() { if (m_XAxisChanged || !ChartHelper.IsValueEqualsList<XAxis>(m_CheckXAxises, m_XAxises)) { foreach (var axis in m_CheckXAxises) { XAxisPool.Release(axis); } m_CheckXAxises.Clear(); foreach (var axis in m_XAxises) m_CheckXAxises.Add(axis.Clone()); m_XAxisChanged = false; OnXAxisChanged(); } } private void CheckMinMaxValue() { if (m_XAxises == null || m_YAxises == null) return; for (int i = 0; i < m_XAxises.Count; i++) { UpdateAxisMinMaxValue(i, m_XAxises[i]); } for (int i = 0; i < m_YAxises.Count; i++) { UpdateAxisMinMaxValue(i, m_YAxises[i]); } } private void UpdateAxisMinMaxValue(int axisIndex, Axis axis) { if (axis.IsCategory() || !axis.show) return; int tempMinValue = 0; int tempMaxValue = 0; if (IsValue()) { if (axis is XAxis) { m_Series.GetXMinMaxValue(m_DataZoom, axisIndex, true, out tempMinValue, out tempMaxValue); } else { m_Series.GetYMinMaxValue(m_DataZoom, axisIndex, true, out tempMinValue, out tempMaxValue); } } else { m_Series.GetYMinMaxValue(m_DataZoom, axisIndex, false, out tempMinValue, out tempMaxValue); } axis.AdjustMinMaxValue(ref tempMinValue, ref tempMaxValue); if (tempMinValue != axis.minValue || tempMaxValue != axis.maxValue) { m_CheckMinMaxValue = true; axis.minValue = tempMinValue; axis.maxValue = tempMaxValue; axis.zeroXOffset = 0; axis.zeroYOffset = 0; if (tempMinValue != 0 || tempMaxValue != 0) { if (axis is XAxis && axis.IsValue()) { axis.zeroXOffset = axis.minValue > 0 ? 0 : axis.maxValue < 0 ? coordinateWid : Mathf.Abs(axis.minValue) * (coordinateWid / (Mathf.Abs(axis.minValue) + Mathf.Abs(axis.maxValue))); } if (axis is YAxis && axis.IsValue()) { axis.zeroYOffset = axis.minValue > 0 ? 0 : axis.maxValue < 0 ? coordinateHig : Mathf.Abs(axis.minValue) * (coordinateHig / (Mathf.Abs(axis.minValue) + Mathf.Abs(axis.maxValue))); } } float coordinateWidth = axis is XAxis ? coordinateWid : coordinateHig; axis.UpdateLabelText(coordinateWidth, m_DataZoom); RefreshChart(); } } protected virtual void OnCoordinateChanged() { InitAxisX(); InitAxisY(); } protected virtual void OnYAxisChanged() { InitAxisY(); } protected virtual void OnXAxisChanged() { InitAxisX(); } protected override void OnSizeChanged() { base.OnSizeChanged(); InitAxisX(); InitAxisY(); } private void DrawCoordinate(VertexHelper vh) { DrawGrid(vh); for (int i = 0; i < m_XAxises.Count; i++) { DrawXAxisTickAndSplit(vh, i, m_XAxises[i]); } for (int i = 0; i < m_YAxises.Count; i++) { DrawYAxisTickAndSplit(vh, i, m_YAxises[i]); } for (int i = 0; i < m_XAxises.Count; i++) { DrawXAxisLine(vh, i, m_XAxises[i]); } for (int i = 0; i < m_YAxises.Count; i++) { DrawYAxisLine(vh, i, m_YAxises[i]); } } private void DrawGrid(VertexHelper vh) { if (m_Grid.show && m_Grid.backgroundColor != Color.clear) { var p1 = new Vector2(coordinateX, coordinateY); var p2 = new Vector2(coordinateX, coordinateY + coordinateHig); var p3 = new Vector2(coordinateX + coordinateWid, coordinateY + coordinateHig); var p4 = new Vector2(coordinateX + coordinateWid, coordinateY); ChartDrawer.DrawPolygon(vh, p1, p2, p3, p4, m_Grid.backgroundColor); } } private void DrawYAxisTickAndSplit(VertexHelper vh, int yAxisIndex, YAxis yAxis) { if (yAxis.show) { var size = yAxis.GetScaleNumber(coordinateWid, m_DataZoom); var totalWidth = coordinateY; var xAxis = m_XAxises[yAxisIndex]; var zeroPos = new Vector3(coordinateX + xAxis.zeroXOffset, coordinateY + yAxis.zeroYOffset); for (int i = 0; i < size; i++) { var scaleWidth = yAxis.GetScaleWidth(coordinateHig, i, m_DataZoom); float pX = 0; float pY = totalWidth; if (yAxis.boundaryGap && yAxis.axisTick.alignWithLabel) { pY -= scaleWidth / 2; } if (yAxis.splitArea.show && i < size - 1) { ChartDrawer.DrawPolygon(vh, new Vector2(coordinateX, pY), new Vector2(coordinateX + coordinateWid, pY), new Vector2(coordinateX + coordinateWid, pY + scaleWidth), new Vector2(coordinateX, pY + scaleWidth), yAxis.splitArea.getColor(i)); } if (yAxis.axisTick.show) { var startX = coordinateX + m_XAxises[yAxisIndex].zeroXOffset; if (yAxis.IsValue() && yAxisIndex > 0) startX += coordinateWid; bool inside = yAxis.axisTick.inside; if ((inside && yAxisIndex == 0) || (!inside && yAxisIndex == 1)) { pX += startX + yAxis.axisTick.length; } else { pX += startX - yAxis.axisTick.length; } ChartDrawer.DrawLine(vh, new Vector3(startX, pY), new Vector3(pX, pY), yAxis.axisLine.width, m_ThemeInfo.axisLineColor); } if (yAxis.showSplitLine) { if (!xAxis.axisLine.show || zeroPos.y != pY) { DrawSplitLine(vh, yAxis, yAxis.splitLineType, new Vector3(coordinateX, pY), new Vector3(coordinateX + coordinateWid, pY), m_ThemeInfo.axisSplitLineColor); } } totalWidth += scaleWidth; } } } private void DrawXAxisTickAndSplit(VertexHelper vh, int xAxisIndex, XAxis xAxis) { if (xAxis.show) { var size = xAxis.GetScaleNumber(coordinateWid, m_DataZoom); var totalWidth = coordinateX; var yAxis = m_YAxises[xAxisIndex]; var zeroPos = new Vector3(coordinateX, coordinateY + yAxis.zeroYOffset); for (int i = 0; i < size; i++) { var scaleWidth = xAxis.GetScaleWidth(coordinateWid, i, m_DataZoom); float pX = totalWidth; float pY = 0; if (xAxis.boundaryGap && xAxis.axisTick.alignWithLabel) { pX -= scaleWidth / 2; } if (xAxis.splitArea.show && i < size - 1) { ChartDrawer.DrawPolygon(vh, new Vector2(pX, coordinateY), new Vector2(pX, coordinateY + coordinateHig), new Vector2(pX + scaleWidth, coordinateY + coordinateHig), new Vector2(pX + scaleWidth, coordinateY), xAxis.splitArea.getColor(i)); } if (xAxis.axisTick.show) { var startY = coordinateY + m_YAxises[xAxisIndex].zeroYOffset; if (xAxis.IsValue() && xAxisIndex > 0) startY += coordinateHig; bool inside = xAxis.axisTick.inside; if ((inside && xAxisIndex == 0) || (!inside && xAxisIndex == 1)) { pY += startY + xAxis.axisTick.length; } else { pY += startY - xAxis.axisTick.length; } ChartDrawer.DrawLine(vh, new Vector3(pX, startY), new Vector3(pX, pY), xAxis.axisLine.width, m_ThemeInfo.axisLineColor); } if (xAxis.showSplitLine) { if (!yAxis.axisLine.show || zeroPos.x != pX) { DrawSplitLine(vh, xAxis, xAxis.splitLineType, new Vector3(pX, coordinateY), new Vector3(pX, coordinateY + coordinateHig), m_ThemeInfo.axisSplitLineColor); } } totalWidth += scaleWidth; } } } private void DrawXAxisLine(VertexHelper vh, int xAxisIndex, XAxis xAxis) { if (xAxis.show && xAxis.axisLine.show) { var lineY = coordinateY + (xAxis.axisLine.onZero ? m_YAxises[xAxisIndex].zeroYOffset : 0); if (xAxis.IsValue() && xAxisIndex > 0) lineY += coordinateHig; var left = new Vector3(coordinateX - xAxis.axisLine.width, lineY); var top = new Vector3(coordinateX + coordinateWid + xAxis.axisLine.width, lineY); ChartDrawer.DrawLine(vh, left, top, xAxis.axisLine.width, m_ThemeInfo.axisLineColor); if (xAxis.axisLine.symbol) { var axisLine = xAxis.axisLine; ChartDrawer.DrawArrow(vh, new Vector3(coordinateX, lineY), top, axisLine.symbolWidth, axisLine.symbolHeight, axisLine.symbolOffset, axisLine.symbolDent, m_ThemeInfo.axisLineColor); } } } private void DrawYAxisLine(VertexHelper vh, int yAxisIndex, YAxis yAxis) { if (yAxis.show && yAxis.axisLine.show) { var lineX = coordinateX + (yAxis.axisLine.onZero ? m_XAxises[yAxisIndex].zeroXOffset : 0); if (yAxis.IsValue() && yAxisIndex > 0) lineX += coordinateWid; var top = new Vector3(lineX, coordinateY + coordinateHig + yAxis.axisLine.width); ChartDrawer.DrawLine(vh, new Vector3(lineX, coordinateY - yAxis.axisLine.width), top, yAxis.axisLine.width, m_ThemeInfo.axisLineColor); if (yAxis.axisLine.symbol) { var axisLine = yAxis.axisLine; ChartDrawer.DrawArrow(vh, new Vector3(lineX, coordinateX), top, axisLine.symbolWidth, axisLine.symbolHeight, axisLine.symbolOffset, axisLine.symbolDent, m_ThemeInfo.axisLineColor); } } } private void DrawDataZoomSlider(VertexHelper vh) { if (!m_DataZoom.enable || !m_DataZoom.supportSlider) return; var hig = m_DataZoom.GetHeight(grid.bottom); var p1 = new Vector2(coordinateX, m_DataZoom.bottom); var p2 = new Vector2(coordinateX, m_DataZoom.bottom + hig); var p3 = new Vector2(coordinateX + coordinateWid, m_DataZoom.bottom + hig); var p4 = new Vector2(coordinateX + coordinateWid, m_DataZoom.bottom); var xAxis = xAxises[0]; ChartDrawer.DrawLine(vh, p1, p2, xAxis.axisLine.width, m_ThemeInfo.dataZoomLineColor); ChartDrawer.DrawLine(vh, p2, p3, xAxis.axisLine.width, m_ThemeInfo.dataZoomLineColor); ChartDrawer.DrawLine(vh, p3, p4, xAxis.axisLine.width, m_ThemeInfo.dataZoomLineColor); ChartDrawer.DrawLine(vh, p4, p1, xAxis.axisLine.width, m_ThemeInfo.dataZoomLineColor); if (m_DataZoom.showDataShadow && m_Series.Count > 0) { Serie serie = m_Series.list[0]; Axis axis = yAxises[0]; var showData = serie.GetDataList(null); float scaleWid = coordinateWid / (showData.Count - 1); Vector3 lp = Vector3.zero; Vector3 np = Vector3.zero; int minValue = 0; int maxValue = 0; m_Series.GetYMinMaxValue(null, 0, IsValue(), out minValue, out maxValue); axis.AdjustMinMaxValue(ref minValue, ref maxValue); int rate = 1; var sampleDist = serie.sampleDist < 2 ? 2 : serie.sampleDist; var maxCount = showData.Count; if (sampleDist > 0) rate = (int)((maxCount - serie.minShow) / (coordinateWid / sampleDist)); if (rate < 1) rate = 1; var totalAverage = serie.sampleAverage > 0 ? serie.sampleAverage : DataAverage(ref showData, serie.sampleType, serie.minShow, maxCount, rate); for (int i = 0; i < maxCount; i += rate) { float value = SampleValue(ref showData, serie.sampleType, rate, serie.minShow, maxCount, totalAverage, i); float pX = coordinateX + i * scaleWid; float dataHig = (axis.maxValue - axis.minValue) == 0 ? 0 : (value - axis.minValue) / (axis.maxValue - axis.minValue) * hig; np = new Vector3(pX, m_DataZoom.bottom + dataHig); if (i > 0) { Color color = m_ThemeInfo.dataZoomLineColor; ChartDrawer.DrawLine(vh, lp, np, xAxis.axisLine.width, color); Vector3 alp = new Vector3(lp.x, lp.y - xAxis.axisLine.width); Vector3 anp = new Vector3(np.x, np.y - xAxis.axisLine.width); Color areaColor = new Color(color.r, color.g, color.b, color.a * 0.75f); Vector3 tnp = new Vector3(np.x, m_DataZoom.bottom + xAxis.axisLine.width); Vector3 tlp = new Vector3(lp.x, m_DataZoom.bottom + xAxis.axisLine.width); ChartDrawer.DrawPolygon(vh, alp, anp, tnp, tlp, areaColor); } lp = np; } } switch (m_DataZoom.rangeMode) { case DataZoom.RangeMode.Percent: var start = coordinateX + coordinateWid * m_DataZoom.start / 100; var end = coordinateX + coordinateWid * m_DataZoom.end / 100; p1 = new Vector2(start, m_DataZoom.bottom); p2 = new Vector2(start, m_DataZoom.bottom + hig); p3 = new Vector2(end, m_DataZoom.bottom + hig); p4 = new Vector2(end, m_DataZoom.bottom); ChartDrawer.DrawPolygon(vh, p1, p2, p3, p4, m_ThemeInfo.dataZoomSelectedColor); ChartDrawer.DrawLine(vh, p1, p2, xAxis.axisLine.width, m_ThemeInfo.dataZoomSelectedColor); ChartDrawer.DrawLine(vh, p3, p4, xAxis.axisLine.width, m_ThemeInfo.dataZoomSelectedColor); break; } } protected void DrawSplitLine(VertexHelper vh, Axis axis, Axis.SplitLineType type, Vector3 startPos, Vector3 endPos, Color color) { switch (type) { case Axis.SplitLineType.Dashed: ChartDrawer.DrawDashLine(vh, startPos, endPos, axis.axisLine.width, color); break; case Axis.SplitLineType.Dotted: ChartDrawer.DrawDotLine(vh, startPos, endPos, axis.axisLine.width, color); break; case Axis.SplitLineType.Solid: ChartDrawer.DrawLine(vh, startPos, endPos, axis.axisLine.width, color); break; case Axis.SplitLineType.DashDot: ChartDrawer.DrawDashDotLine(vh, startPos, endPos, axis.axisLine.width, color); break; case Axis.SplitLineType.DashDotDot: ChartDrawer.DrawDashDotDotLine(vh, startPos, endPos, axis.axisLine.width, color); break; } } protected void DrawXTooltipIndicator(VertexHelper vh) { if (!m_Tooltip.show || !m_Tooltip.IsSelected()) return; if (m_Tooltip.type == Tooltip.Type.None) return; for (int i = 0; i < m_XAxises.Count; i++) { var xAxis = m_XAxises[i]; var yAxis = m_YAxises[i]; if (!xAxis.show) continue; float splitWidth = xAxis.GetDataWidth(coordinateWid, m_DataZoom); switch (m_Tooltip.type) { case Tooltip.Type.Corss: case Tooltip.Type.Line: float pX = coordinateX + m_Tooltip.xValues[i] * splitWidth + (xAxis.boundaryGap ? splitWidth / 2 : 0); if (xAxis.IsValue()) pX = m_Tooltip.pointerPos.x; Vector2 sp = new Vector2(pX, coordinateY); Vector2 ep = new Vector2(pX, coordinateY + coordinateHig); DrawSplitLine(vh, xAxis, Axis.SplitLineType.Solid, sp, ep, m_ThemeInfo.tooltipLineColor); if (m_Tooltip.type == Tooltip.Type.Corss) { sp = new Vector2(coordinateX, m_Tooltip.pointerPos.y); ep = new Vector2(coordinateX + coordinateWid, m_Tooltip.pointerPos.y); DrawSplitLine(vh, yAxis, Axis.SplitLineType.Dashed, sp, ep, m_ThemeInfo.tooltipLineColor); } break; case Tooltip.Type.Shadow: float tooltipSplitWid = splitWidth < 1 ? 1 : splitWidth; pX = coordinateX + splitWidth * m_Tooltip.xValues[i] - (xAxis.boundaryGap ? 0 : splitWidth / 2); if (xAxis.IsValue()) pX = m_Tooltip.xValues[i]; float pY = coordinateY + coordinateHig; Vector3 p1 = new Vector3(pX, coordinateY); Vector3 p2 = new Vector3(pX, pY); Vector3 p3 = new Vector3(pX + tooltipSplitWid, pY); Vector3 p4 = new Vector3(pX + tooltipSplitWid, coordinateY); ChartDrawer.DrawPolygon(vh, p1, p2, p3, p4, m_ThemeInfo.tooltipFlagAreaColor); break; } } } protected void DrawYTooltipIndicator(VertexHelper vh) { if (!m_Tooltip.show || !m_Tooltip.IsSelected()) return; if (m_Tooltip.type == Tooltip.Type.None) return; for (int i = 0; i < m_YAxises.Count; i++) { var yAxis = m_YAxises[i]; var xAxis = m_XAxises[i]; if (!yAxis.show) continue; float splitWidth = yAxis.GetDataWidth(coordinateHig, m_DataZoom); switch (m_Tooltip.type) { case Tooltip.Type.Corss: case Tooltip.Type.Line: float pY = coordinateY + m_Tooltip.yValues[i] * splitWidth + (yAxis.boundaryGap ? splitWidth / 2 : 0); Vector2 sp = new Vector2(coordinateX, pY); Vector2 ep = new Vector2(coordinateX + coordinateWid, pY); DrawSplitLine(vh, xAxis, Axis.SplitLineType.Solid, sp, ep, m_ThemeInfo.tooltipLineColor); if (m_Tooltip.type == Tooltip.Type.Corss) { sp = new Vector2(coordinateX, m_Tooltip.pointerPos.y); ep = new Vector2(coordinateX + coordinateWid, m_Tooltip.pointerPos.y); DrawSplitLine(vh, yAxis, Axis.SplitLineType.Dashed, sp, ep, m_ThemeInfo.tooltipLineColor); } break; case Tooltip.Type.Shadow: float tooltipSplitWid = splitWidth < 1 ? 1 : splitWidth; float pX = coordinateX + coordinateWid; pY = coordinateY + splitWidth * m_Tooltip.yValues[i] - (yAxis.boundaryGap ? 0 : splitWidth / 2); Vector3 p1 = new Vector3(coordinateX, pY); Vector3 p2 = new Vector3(coordinateX, pY + tooltipSplitWid); Vector3 p3 = new Vector3(pX, pY + tooltipSplitWid); Vector3 p4 = new Vector3(pX, pY); ChartDrawer.DrawPolygon(vh, p1, p2, p3, p4, m_ThemeInfo.tooltipFlagAreaColor); break; } } } private void CheckDataZoom() { if (raycastTarget != m_DataZoom.enable) { raycastTarget = m_DataZoom.enable; } if (!m_DataZoom.enable) return; CheckDataZoomScale(); CheckDataZoomLabel(); } private bool m_IsSingleTouch; private Vector2 m_LastSingleTouchPos; private Vector2 m_LastTouchPos0; private Vector2 m_LastTouchPos1; private void CheckDataZoomScale() { if (!m_DataZoom.enable || m_DataZoom.zoomLock || !m_DataZoom.supportInside) return; if (Input.touchCount == 2) { var touch0 = Input.GetTouch(0); var touch1 = Input.GetTouch(1); if (touch1.phase == TouchPhase.Began) { m_LastTouchPos0 = touch0.position; m_LastTouchPos1 = touch1.position; } else if (touch0.phase == TouchPhase.Moved || touch1.phase == TouchPhase.Moved) { var tempPos0 = touch0.position; var tempPos1 = touch1.position; var currDist = Vector2.Distance(tempPos0, tempPos1); var lastDist = Vector2.Distance(m_LastTouchPos0, m_LastTouchPos1); var delta = (currDist - lastDist); ScaleDataZoom(delta / m_DataZoom.scrollSensitivity); m_LastTouchPos0 = tempPos0; m_LastTouchPos1 = tempPos1; } } } private void CheckDataZoomLabel() { if (m_DataZoom.supportSlider && m_DataZoom.showDetail) { Vector2 local; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, canvas.worldCamera, out local)) { m_DataZoom.SetLabelActive(false); return; } if (m_DataZoom.IsInSelectedZoom(local, coordinateX, coordinateWid) || m_DataZoom.IsInStartZoom(local, coordinateX, coordinateWid) || m_DataZoom.IsInEndZoom(local, coordinateX, coordinateWid)) { m_DataZoom.SetLabelActive(true); RefreshDataZoomLabel(); } else { m_DataZoom.SetLabelActive(false); } } if (m_CheckDataZoomLabel) { m_CheckDataZoomLabel = false; var xAxis = m_XAxises[m_DataZoom.xAxisIndex]; var startIndex = (int)((xAxis.data.Count - 1) * m_DataZoom.start / 100); var endIndex = (int)((xAxis.data.Count - 1) * m_DataZoom.end / 100); if (m_DataZoomLastStartIndex != startIndex || m_DataZoomLastEndIndex != endIndex) { m_DataZoomLastStartIndex = startIndex; m_DataZoomLastEndIndex = endIndex; if (xAxis.data.Count > 0) { m_DataZoom.SetStartLabelText(xAxis.data[startIndex]); m_DataZoom.SetEndLabelText(xAxis.data[endIndex]); } InitAxisX(); } var start = coordinateX + coordinateWid * m_DataZoom.start / 100; var end = coordinateX + coordinateWid * m_DataZoom.end / 100; var hig = m_DataZoom.GetHeight(grid.bottom); m_DataZoom.startLabel.transform.localPosition = new Vector3(start - 10, m_DataZoom.bottom + hig / 2); m_DataZoom.endLabel.transform.localPosition = new Vector3(end + 10, m_DataZoom.bottom + hig / 2); } } protected void DrawLabelBackground(VertexHelper vh) { var isYAxis = m_YAxises[0].type == Axis.AxisType.Category || m_YAxises[1].type == Axis.AxisType.Category; for (int n = 0; n < m_Series.Count; n++) { var serie = m_Series.GetSerie(n); if (!serie.show) continue; var zeroPos = Vector3.zero; var lastStackSerie = m_Series.GetLastStackSerie(n); if (serie.type == SerieType.Bar) { if (serie.label.position == SerieLabel.Position.Bottom || serie.label.position == SerieLabel.Position.Center) { if (isYAxis) { var xAxis = m_XAxises[serie.axisIndex]; zeroPos = new Vector3(coordinateX + xAxis.zeroXOffset, coordinateY); } else { var yAxis = m_YAxises[serie.axisIndex]; zeroPos = new Vector3(coordinateX, coordinateY + yAxis.zeroYOffset); } } } for (int j = 0; j < serie.data.Count; j++) { var serieData = serie.data[j]; if (serie.label.show || serieData.showIcon) { var pos = serie.dataPoints[j]; var value = serieData.data[1]; switch (serie.type) { case SerieType.Line: break; case SerieType.Bar: var bottomPos = lastStackSerie == null ? zeroPos : lastStackSerie.dataPoints[j]; switch (serie.label.position) { case SerieLabel.Position.Center: pos = isYAxis ? new Vector3(bottomPos.x + (pos.x - bottomPos.x) / 2, pos.y) : new Vector3(pos.x, bottomPos.y + (pos.y - bottomPos.y) / 2); break; case SerieLabel.Position.Bottom: pos = isYAxis ? new Vector3(bottomPos.x, pos.y) : new Vector3(pos.x, bottomPos.y); break; } break; } serieData.labelPosition = pos; if (serie.label.show) DrawLabelBackground(vh, serie, serieData); } else { serieData.SetLabelActive(false); } } } } protected override void OnRefreshLabel() { for (int i = 0; i < m_Series.Count; i++) { var serie = m_Series.GetSerie(i); var total = serie.yTotal; for (int j = 0; j < serie.data.Count; j++) { if (j >= serie.dataPoints.Count) break; var serieData = serie.data[j]; var pos = serie.dataPoints[j]; serieData.SetGameObjectPosition(serieData.labelPosition); serieData.UpdateIcon(); if (serie.show && serie.label.show) { var value = serieData.data[1]; var content = serie.label.GetFormatterContent(serie.name, serieData.name, value, total); serieData.SetLabelActive(true); serieData.SetLabelPosition(serie.label.offset); if (serieData.SetLabelText(content)) RefreshChart(); } else { serieData.SetLabelActive(false); } } } } public override void OnBeginDrag(PointerEventData eventData) { if (Input.touchCount > 1) return; Vector2 pos; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, canvas.worldCamera, out pos)) { return; } if (m_DataZoom.supportInside) { if (IsInCooridate(pos)) { m_DataZoom.isDraging = true; m_DataZoomCoordinateDrag = true; } } if (m_DataZoom.supportSlider) { if (m_DataZoom.IsInStartZoom(pos, coordinateX, coordinateWid)) { m_DataZoom.isDraging = true; m_DataZoomStartDrag = true; } else if (m_DataZoom.IsInEndZoom(pos, coordinateX, coordinateWid)) { m_DataZoom.isDraging = true; m_DataZoomEndDrag = true; } else if (m_DataZoom.IsInSelectedZoom(pos, coordinateX, coordinateWid)) { m_DataZoom.isDraging = true; m_DataZoomDrag = true; } } } public override void OnDrag(PointerEventData eventData) { if (Input.touchCount > 1) return; float deltaX = eventData.delta.x; float deltaPercent = deltaX / coordinateWid * 100; OnDragInside(deltaPercent); OnDragSlider(deltaPercent); } private void OnDragInside(float deltaPercent) { if (Input.touchCount > 1) return; if (!m_DataZoom.supportInside) return; if (!m_DataZoomCoordinateDrag) return; var diff = m_DataZoom.end - m_DataZoom.start; if (deltaPercent > 0) { m_DataZoom.start -= deltaPercent; m_DataZoom.end = m_DataZoom.start + diff; } else { m_DataZoom.end += -deltaPercent; m_DataZoom.start = m_DataZoom.end - diff; } RefreshDataZoomLabel(); RefreshChart(); } private void OnDragSlider(float deltaPercent) { if (Input.touchCount > 1) return; if (!m_DataZoom.supportSlider) return; if (m_DataZoomStartDrag) { m_DataZoom.start += deltaPercent; if (m_DataZoom.start > m_DataZoom.end) { m_DataZoom.start = m_DataZoom.end; m_DataZoomEndDrag = true; m_DataZoomStartDrag = false; } if (m_DataZoom.realtime) { RefreshDataZoomLabel(); RefreshChart(); } } else if (m_DataZoomEndDrag) { m_DataZoom.end += deltaPercent; if (m_DataZoom.end < m_DataZoom.start) { m_DataZoom.end = m_DataZoom.start; m_DataZoomStartDrag = true; m_DataZoomEndDrag = false; } if (m_DataZoom.realtime) { RefreshDataZoomLabel(); RefreshChart(); } } else if (m_DataZoomDrag) { if (deltaPercent > 0) { if (m_DataZoom.end + deltaPercent > 100) { deltaPercent = 100 - m_DataZoom.end; } } else { if (m_DataZoom.start + deltaPercent < 0) { deltaPercent = -m_DataZoom.start; } } m_DataZoom.start += deltaPercent; m_DataZoom.end += deltaPercent; if (m_DataZoom.realtime) { RefreshDataZoomLabel(); RefreshChart(); } } } private void RefreshDataZoomLabel() { m_CheckDataZoomLabel = true; } public override void OnEndDrag(PointerEventData eventData) { if (m_DataZoomDrag || m_DataZoomStartDrag || m_DataZoomEndDrag || m_DataZoomCoordinateDrag) { RefreshChart(); } m_DataZoomDrag = false; m_DataZoomCoordinateDrag = false; m_DataZoomStartDrag = false; m_DataZoomEndDrag = false; m_DataZoom.isDraging = false; } public override void OnPointerDown(PointerEventData eventData) { if (Input.touchCount > 1) return; Vector2 localPos; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, canvas.worldCamera, out localPos)) { return; } if (m_DataZoom.IsInStartZoom(localPos, coordinateX, coordinateWid) || m_DataZoom.IsInEndZoom(localPos, coordinateX, coordinateWid)) { return; } if (m_DataZoom.IsInZoom(localPos, coordinateX, coordinateWid) && !m_DataZoom.IsInSelectedZoom(localPos, coordinateX, coordinateWid)) { var pointerX = localPos.x; var selectWidth = coordinateWid * (m_DataZoom.end - m_DataZoom.start) / 100; var startX = pointerX - selectWidth / 2; var endX = pointerX + selectWidth / 2; if (startX < coordinateX) { startX = coordinateX; endX = coordinateX + selectWidth; } else if (endX > coordinateX + coordinateWid) { endX = coordinateX + coordinateWid; startX = coordinateX + coordinateWid - selectWidth; } m_DataZoom.start = (startX - coordinateX) / coordinateWid * 100; m_DataZoom.end = (endX - coordinateX) / coordinateWid * 100; RefreshDataZoomLabel(); RefreshChart(); } } public override void OnScroll(PointerEventData eventData) { if (Input.touchCount > 1) return; if (!m_DataZoom.enable || m_DataZoom.zoomLock || !m_DataZoom.supportInside) return; Vector2 pos; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, canvas.worldCamera, out pos)) { return; } if (!IsInCooridate(pos)) { return; } ScaleDataZoom(eventData.scrollDelta.y * m_DataZoom.scrollSensitivity); } private void ScaleDataZoom(float delta) { float deltaPercent = Mathf.Abs(delta / coordinateWid * 100); if (delta > 0) { if (m_DataZoom.end <= m_DataZoom.start) return; m_DataZoom.end -= deltaPercent; m_DataZoom.start += deltaPercent; if (m_DataZoom.end <= m_DataZoom.start) { m_DataZoom.end = m_DataZoom.start; } } else { m_DataZoom.end += deltaPercent; m_DataZoom.start -= deltaPercent; if (m_DataZoom.end > 100) m_DataZoom.end = 100; if (m_DataZoom.start < 0) m_DataZoom.start = 0; } RefreshDataZoomLabel(); RefreshChart(); } } }
45.525674
144
0.489645
[ "MIT" ]
muyifan/unity-ugui-XCharts
Assets/XCharts/Scripts/UI/Internal/CoordinateChart.cs
70,933
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Squidex.Infrastructure.Tasks; namespace Squidex.Infrastructure.Commands { public sealed class InMemoryCommandBus : ICommandBus { private readonly List<ICommandMiddleware> handlers; public InMemoryCommandBus(IEnumerable<ICommandMiddleware> handlers) { Guard.NotNull(handlers, nameof(handlers)); this.handlers = handlers.Reverse().ToList(); } public async Task<CommandContext> PublishAsync(ICommand command) { Guard.NotNull(command, nameof(command)); var context = new CommandContext(command); var next = new Func<Task>(() => TaskHelper.Done); foreach (var handler in handlers) { next = Join(handler, context, next); } await next(); return context; } private static Func<Task> Join(ICommandMiddleware handler, CommandContext context, Func<Task> next) { return () => handler.HandleAsync(context, next); } } }
30.52
107
0.532765
[ "MIT" ]
blakecodes/squidex
src/Squidex.Infrastructure/Commands/InMemoryCommandBus.cs
1,529
C#
// // IntrinsicInteger.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2016 Tomona Nanase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Numerics; using static Lury.Engine.Intrinsic.IntrinsicIntrinsic; using static Lury.Engine.Intrinsic.IntrinsicBoolean; namespace Lury.Engine.Intrinsic { [IntrinsicClass(FullName, TypeName)] class IntrinsicInteger { #region -- Public Fields -- public const string FullName = "lury.core.Integer"; public const string TypeName = "Integer"; #endregion #region -- Public Static Methods -- public static LuryObject GetObject(BigInteger value) { return new LuryObject(FullName, value, freeze: true); } [Intrinsic(OperatorPow)] public static LuryObject Pow(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) { var exponent = (BigInteger)other.Value; if (exponent > int.MaxValue || exponent < int.MinValue) return IntrinsicReal.GetObject(Math.Pow((double)(BigInteger)self.Value, (double)exponent)); else return GetObject(BigInteger.Pow((BigInteger)self.Value, (int)exponent)); } else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject(Math.Pow((double)(BigInteger)self.Value, (double)other.Value)); else if (other.LuryTypeName == IntrinsicComplex.FullName) return IntrinsicComplex.GetObject(Complex.Pow((double)(BigInteger)self.Value, (Complex)other.Value)); else throw new ArgumentException(); } [Intrinsic(OperatorInc)] public static LuryObject Inc(LuryObject self) { return GetObject((BigInteger)self.Value + 1); } [Intrinsic(OperatorDec)] public static LuryObject Dec(LuryObject self) { return GetObject((BigInteger)self.Value - 1); } [Intrinsic(OperatorPos)] public static LuryObject Pos(LuryObject self) { return self; } [Intrinsic(OperatorNeg)] public static LuryObject Neg(LuryObject self) { return GetObject(-(BigInteger)self.Value); } [Intrinsic(OperatorInv)] public static LuryObject Inv(LuryObject self) { return GetObject(~(BigInteger)self.Value); } [Intrinsic(OperatorMul)] public static LuryObject Mul(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return GetObject((BigInteger)self.Value * (BigInteger)other.Value); else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value * (double)other.Value); else if (other.LuryTypeName == IntrinsicComplex.FullName) return IntrinsicComplex.GetObject((double)(BigInteger)self.Value * (Complex)other.Value); else throw new ArgumentException(); } [Intrinsic(OperatorDiv)] public static LuryObject Div(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); if (other.LuryTypeName == FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value / (double)(BigInteger)other.Value); else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value / (double)other.Value); else if (other.LuryTypeName == IntrinsicComplex.FullName) return IntrinsicComplex.GetObject((double)(BigInteger)self.Value / (Complex)other.Value); else throw new ArgumentException(); } [Intrinsic(OperatorIDiv)] public static LuryObject IDiv(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); if (other.LuryTypeName == FullName) return GetObject((BigInteger)self.Value / (BigInteger)other.Value); else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value / (double)other.Value); else if (other.LuryTypeName == IntrinsicComplex.FullName) return IntrinsicComplex.GetObject((double)(BigInteger)self.Value / (Complex)other.Value); else throw new ArgumentException(); } [Intrinsic(OperatorMod)] public static LuryObject Mod(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return GetObject((BigInteger)self.Value % (BigInteger)other.Value); else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value % (double)other.Value); // if (other.LuryTypeName == IntrinsicComplex.FullName) else throw new ArgumentException(); } [Intrinsic(OperatorAdd)] public static LuryObject Add(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return GetObject((BigInteger)self.Value + (BigInteger)other.Value); else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value + (double)other.Value); else if (other.LuryTypeName == IntrinsicComplex.FullName) return IntrinsicComplex.GetObject((double)(BigInteger)self.Value + (Complex)other.Value); else throw new ArgumentException(); } [Intrinsic(OperatorSub)] public static LuryObject Sub(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return GetObject((BigInteger)self.Value - (BigInteger)other.Value); else if (other.LuryTypeName == IntrinsicReal.FullName) return IntrinsicReal.GetObject((double)(BigInteger)self.Value - (double)other.Value); else if (other.LuryTypeName == IntrinsicComplex.FullName) return IntrinsicComplex.GetObject((double)(BigInteger)self.Value - (Complex)other.Value); else throw new ArgumentException(); } [Intrinsic(OperatorLShift)] public static LuryObject LShift(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); return GetObject((BigInteger)self.Value << (int)((BigInteger)other.Value)); } [Intrinsic(OperatorRShift)] public static LuryObject RShift(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); return GetObject((BigInteger)self.Value >> (int)((BigInteger)other.Value)); } [Intrinsic(OperatorAnd)] public static LuryObject And(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); return GetObject((BigInteger)self.Value & (BigInteger)other.Value); } [Intrinsic(OperatorXor)] public static LuryObject Xor(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); return GetObject((BigInteger)self.Value ^ (BigInteger)other.Value); } [Intrinsic(OperatorOr)] public static LuryObject Or(LuryObject self, LuryObject other) { if (other.LuryTypeName != FullName) throw new ArgumentException(); return GetObject((BigInteger)self.Value | (BigInteger)other.Value); } [Intrinsic(OperatorEq)] public static LuryObject Equals(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return (BigInteger)self.Value == (BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicReal.FullName) return (double)(BigInteger)self.Value == (double)(BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicComplex.FullName) return (Complex)(double)(BigInteger)self.Value == (Complex)(double)(BigInteger)other.Value ? True : False; else throw new ArgumentException(); } [Intrinsic(OperatorNe)] public static LuryObject NotEqual(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return (BigInteger)self.Value != (BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicReal.FullName) return (double)(BigInteger)self.Value != (double)(BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicComplex.FullName) return (Complex)(double)(BigInteger)self.Value != (Complex)(double)(BigInteger)other.Value ? True : False; else throw new ArgumentException(); } [Intrinsic(OperatorLt)] public static LuryObject Lt(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return (BigInteger)self.Value < (BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicReal.FullName) return (double)(BigInteger)self.Value < (double)(BigInteger)other.Value ? True : False; else throw new ArgumentException(); } [Intrinsic(OperatorLtq)] public static LuryObject Ltq(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return (BigInteger)self.Value <= (BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicReal.FullName) return (double)(BigInteger)self.Value <= (double)(BigInteger)other.Value ? True : False; else throw new ArgumentException(); } [Intrinsic(OperatorGt)] public static LuryObject Gt(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return (BigInteger)self.Value > (BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicReal.FullName) return (double)(BigInteger)self.Value > (double)(BigInteger)other.Value ? True : False; else throw new ArgumentException(); } [Intrinsic(OperatorGtq)] public static LuryObject Gtq(LuryObject self, LuryObject other) { if (other.LuryTypeName == FullName) return (BigInteger)self.Value >= (BigInteger)other.Value ? True : False; else if (other.LuryTypeName == IntrinsicReal.FullName) return (double)(BigInteger)self.Value >= (double)(BigInteger)other.Value ? True : False; else throw new ArgumentException(); } #endregion } }
41.619672
122
0.620529
[ "MIT" ]
lury-lang/lury-ir
LuryIR/Engine/Intrinsic/IntrinsicInteger.cs
12,696
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; /** this class is able to load a recordet data file and playback the laoded data */ public class PlayerScript : MonoBehaviour { public class TrackingDataPoint { public int id; public int condition; public long time; public Vector3 hmdPosition; public Quaternion hmdRotation; public Vector3 shoulder1Position; public Vector3 shoulder2Position; public Quaternion shoulder1Rotation; public Quaternion shoulder2Rotation; public Vector3 forearmPosition; public Quaternion forearmRotation; public Vector3 handPosition; public Quaternion handRotation; public Vector3 indexPosition; public Quaternion indexRotation; } public class Click { public long time; public float x; public float y; } public GameObject canvas; //recorded data objects public Int32 Id; public Int32 versionId; //0: outside project; 1: test data; 2: inside project public int fileType; public string date; public GameObject hmd; public GameObject TshirtRoot; public GameObject TshirtForearmBone; public GameObject TshirtUpperArm; public GameObject forearmBone; public GameObject handBone; public GameObject indexFingerBone; public GameObject TestShoulder; private PositionScript canvasPosition; private List<TrackingDataPoint> trackingData; private List<Click> clickData; private int currentDataPoint = 0; private int currentClickIndex = 0; private string FilePath; // Use this for initialization void Start () { Application.targetFrameRate = 90; if(fileType == 0) { FilePath = "C:\\Users\\schweigern\\Desktop\\Builds\\OutputData\\"; } else if(fileType == 1) { FilePath = "C:\\Users\\schweigern\\Desktop\\PintingInVR\\pointinginvr\\TestData\\" + date + "\\"; } else if(fileType == 2) { FilePath = "Assets/OutputData/"; } canvasPosition = (PositionScript)canvas.GetComponent(typeof(PositionScript)); canvasPosition.setTargetVisibility(true); trackingData = new List<TrackingDataPoint>(); clickData = new List<Click>(); FileStream dataFile; FileStream clickFile; FileStream rawFile; if (fileType == 1) { dataFile = File.OpenRead(FilePath + Id + "boneData_" + versionId + ".csv"); clickFile = File.OpenRead(FilePath + Id + "clickData_" + versionId + ".csv"); rawFile = File.OpenRead(FilePath + Id + "rawData_" + versionId + ".csv"); } else { dataFile = File.OpenRead(FilePath + "BoneData\\" + Id + "boneData_" + versionId + ".csv"); clickFile = File.OpenRead(FilePath + "ClickData\\" + Id + "clickData_" + versionId + ".csv"); rawFile = File.OpenRead(FilePath + "RawData\\" + Id + "rawData_" + versionId + ".csv"); } var dataReader = new StreamReader(dataFile); var clickReader = new StreamReader(clickFile); var rawReader = new StreamReader(rawFile); bool firstLine = true; while (!dataReader.EndOfStream && !rawReader.EndOfStream) { if (firstLine) { dataReader.ReadLine(); rawReader.ReadLine(); firstLine = false; } else { var readLine = dataReader.ReadLine(); var splitValues = readLine.Split(';'); var rawReadLine = rawReader.ReadLine(); var rawSplitValues = rawReadLine.Split(';'); var tempData = new TrackingDataPoint(); tempData.id = Int32.Parse(splitValues[0]); tempData.time = long.Parse(splitValues[1]); //hmd, position 2 and 3 String[] tempHmdPosition = splitValues[2].Replace("(", "").Replace(")", "").Split(','); String[] tempHmdRotation = splitValues[3].Replace("(", "").Replace(")", "").Split(','); tempData.hmdPosition = new Vector3(float.Parse(tempHmdPosition[0]), float.Parse(tempHmdPosition[1]), float.Parse(tempHmdPosition[2])); tempData.hmdRotation = new Quaternion(float.Parse(tempHmdRotation[0]), float.Parse(tempHmdRotation[1]), float.Parse(tempHmdRotation[2]), float.Parse(tempHmdRotation[3])); //shoulder, position 5 and 6 String[] tempShoulder1Position = splitValues[5].Replace("(", "").Replace(")", "").Split(','); String[] tempShoulder2Position = splitValues[6].Replace("(", "").Replace(")", "").Split(','); tempData.shoulder1Position = new Vector3(float.Parse(tempShoulder1Position[0]), float.Parse(tempShoulder1Position[1]), float.Parse(tempShoulder1Position[2])); tempData.shoulder2Position = new Vector3(float.Parse(tempShoulder2Position[0]), float.Parse(tempShoulder2Position[1]), float.Parse(tempShoulder2Position[2])); //shoulder rot from raw, position 5 and 7 String[] tempShoulder1Rotation = rawSplitValues[9].Replace("(", "").Replace(")", "").Split(','); String[] tempShoulder2Rotation = rawSplitValues[11].Replace("(", "").Replace(")", "").Split(','); tempData.shoulder1Rotation = new Quaternion(float.Parse(tempShoulder1Rotation[0]), float.Parse(tempShoulder1Rotation[1]), float.Parse(tempShoulder1Rotation[2]), float.Parse(tempShoulder1Rotation[3])); tempData.shoulder2Rotation = new Quaternion(float.Parse(tempShoulder2Rotation[0]), float.Parse(tempShoulder2Rotation[1]), float.Parse(tempShoulder2Rotation[2]), float.Parse(tempShoulder2Rotation[3])); //forearm, position 7 and 8 String[] tempForearmPosition = splitValues[7].Replace("(", "").Replace(")", "").Split(','); String[] tempForearmRotation = splitValues[8].Replace("(", "").Replace(")", "").Split(','); tempData.forearmPosition = new Vector3(float.Parse(tempForearmPosition[0]), float.Parse(tempForearmPosition[1]), float.Parse(tempForearmPosition[2])); tempData.forearmRotation = new Quaternion(float.Parse(tempForearmRotation[0]), float.Parse(tempForearmRotation[1]), float.Parse(tempForearmRotation[2]), float.Parse(tempForearmRotation[3])); //hand, position 10 and 11 String[] tempHandPosition = splitValues[10].Replace("(", "").Replace(")", "").Split(','); String[] tempHandRotation = splitValues[11].Replace("(", "").Replace(")", "").Split(','); tempData.handPosition = new Vector3(float.Parse(tempHandPosition[0]), float.Parse(tempHandPosition[1]), float.Parse(tempHandPosition[2])); tempData.handRotation = new Quaternion(float.Parse(tempHandRotation[0]), float.Parse(tempHandRotation[1]), float.Parse(tempHandRotation[2]), float.Parse(tempHandRotation[3])); //index finger, position 13 and 14 String[] tempIndexPosition = splitValues[13].Replace("(", "").Replace(")", "").Split(','); String[] tempIndexRotation = splitValues[14].Replace("(", "").Replace(")", "").Split(','); tempData.indexPosition = new Vector3(float.Parse(tempIndexPosition[0]), float.Parse(tempIndexPosition[1]), float.Parse(tempIndexPosition[2])); tempData.indexRotation = new Quaternion(float.Parse(tempIndexRotation[0]), float.Parse(tempIndexRotation[1]), float.Parse(tempIndexRotation[2]), float.Parse(tempIndexRotation[3])); /* Debug.Log(""); Debug.Log("pos: " + tempHmdPosition); Debug.Log("rot: " + tempHmdRotation); Debug.Log(""); */ trackingData.Add(tempData); } } Debug.Log("number of loaded data points: " + trackingData.Count); int labelCounter = 0; while(!clickReader.EndOfStream) { if (labelCounter < 2) { labelCounter++; clickReader.ReadLine(); } else { Click tempClick = new Click(); String[] tempData = clickReader.ReadLine().Split(';'); tempClick.time = long.Parse(tempData[2]); tempClick.x = float.Parse(tempData[3]); tempClick.y = float.Parse(tempData[4]); clickData.Add(tempClick); } } Debug.Log("loaded " + clickData.Count + " click points"); } // Update is called once per frame void Update () { if (currentDataPoint < trackingData.Count) { //Debug.Log("fps: " + (1 / Time.deltaTime)); //Debug.Log("curr: " + currentDataPoint); var tempData = trackingData[currentDataPoint]; if(TestShoulder != null) { TestShoulder.transform.position = tempData.shoulder2Position; } if(hmd != null) { hmd.transform.position = tempData.hmdPosition; hmd.transform.rotation = tempData.hmdRotation; } if(TshirtRoot != null) { Quaternion newRot = Quaternion.Lerp(tempData.shoulder1Rotation, tempData.shoulder2Rotation, 0.5f); Vector3 shoulderUp = newRot * Vector3.up; Vector3 tempForward = newRot * Vector3.forward; Vector3 newPos = tempData.shoulder1Position + (0.5f * (tempData.shoulder2Position - tempData.shoulder1Position)) - (0.426f * Vector3.Normalize(shoulderUp)) + (0.12f * Vector3.Normalize(tempForward)); TshirtRoot.transform.position = newPos; TshirtRoot.transform.rotation = newRot; } if(TshirtForearmBone != null) { Vector3 forearmUp = tempData.forearmRotation * Vector3.up; Vector3 forearmRight = tempData.forearmRotation * Vector3.right; Vector3 forearmForward = tempData.forearmRotation * Vector3.forward; TshirtForearmBone.transform.rotation = Quaternion.AngleAxis(154.0f, forearmUp) * Quaternion.AngleAxis(180.0f, forearmRight) * tempData.forearmRotation; TshirtForearmBone.transform.position = tempData.forearmPosition - (0.05f * Vector3.Normalize(forearmRight)) + 0.01f * Vector3.Normalize(forearmForward); } if (forearmBone != null) { forearmBone.transform.position = tempData.forearmPosition; forearmBone.transform.rotation = tempData.forearmRotation; } if (handBone != null) { handBone.transform.position = tempData.handPosition; handBone.transform.rotation = tempData.handRotation; } if (indexFingerBone != null) { indexFingerBone.transform.position = tempData.indexPosition; indexFingerBone.transform.rotation = tempData.indexRotation; } currentDataPoint++; if(currentClickIndex < clickData.Count && clickData[currentClickIndex].time <= tempData.time) { canvasPosition.SetTargetPos(new Vector2(clickData[currentClickIndex].x, clickData[currentClickIndex].y)); //Debug.Log("clicked"); currentClickIndex++; } } } }
43.977528
216
0.598535
[ "MIT" ]
interactionlab/pointing-in-vr-hands
Assets/Scripts/PlayerScript.cs
11,744
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2019 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using DaggerfallConnect.FallExe; namespace DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects { /// <summary> /// Repairs equipped items. /// </summary> public class RepairsObjects : BaseEntityEffect { public static readonly string EffectKey = EnchantmentTypes.RepairsObjects.ToString(); const int enchantCost = 900; public override void SetProperties() { properties.Key = EffectKey; properties.GroupName = TextManager.Instance.GetText(textDatabase, EffectKey); properties.AllowedCraftingStations = MagicCraftingStations.ItemMaker; properties.ItemMakerFlags = ItemMakerFlags.SingletonEnchantment | ItemMakerFlags.AllowMultiplePrimaryInstances; } public override EnchantmentSettings[] GetEnchantmentSettings() { EnchantmentSettings[] enchantments = new EnchantmentSettings[1]; enchantments[0] = new EnchantmentSettings() { Version = 1, EffectKey = EffectKey, ClassicType = EnchantmentTypes.RepairsObjects, ClassicParam = -1, PrimaryDisplayName = properties.GroupName, EnchantCost = enchantCost, }; return enchantments; } } }
35.346939
123
0.644342
[ "MIT" ]
concarne000/daggerfall-unity
Assets/Scripts/Game/MagicAndEffects/Effects/Enchanting/RepairsObjects.cs
1,732
C#
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace Kodeistan.Mmg.Model.FHIRV4 { /// <summary> /// Development Status /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum DevelopmentStatus { /// <summary> /// This portion of the specification is not considered to be complete enough or sufficiently /// reviewed to be safe for implementation. It may have known issues or still be in the "in development" stage. /// It is included in the publication as a place-holder, to solicit feedback from the implementation community /// and/orto give implementers some insight as to functionality likely to be included in future versions of the /// specification. Content at this level should only be implemented by the brave or desperate and is very much /// "use at your own risk". The content that is Draft that will usually be elevated to Trial Use once review and /// correction is complete after it has been subjected to ballot /// </summary> [EnumMember(Value = "Draft")] Draft, /// <summary> /// This content has been well reviewed and is considered by the authors to be ready for use in production systems. /// It has been subjected to ballot and approved as an official standard. However, it has not yet seen widespread /// use in production across the full spectrum of environments it is intended to be used in. In some cases, there /// may be documented known issues that require implementation experience to determine appropriate resolutions for. /// Future versions of FHIR may make significant changes to Trial Use content that are not compatible with previously /// published content. /// </summary> [EnumMember(Value = "TrialUse")] TrialUse, /// <summary> /// This content has been subject to review and production implementation in a wide variety of environments. /// The content is considered to be stable and has been 'locked', subjecting it to FHIR Inter-version Compatibility Rules. /// While changes are possible, they are expected to be infrequent and are tightly constrained. /// </summary> [EnumMember(Value = "Normative")] Normative, /// <summary> /// This portion of the specification is provided for implementer assistance and does not make rules that implementers are /// required to follow. Typical examples of this content in the FHIR specification are tables of contents, registries, examples, /// and implementer advice /// </summary> [EnumMember(Value = "Informative")] Informative, /// <summary> /// This portion of the specification is outdated and may be withdrawn in a future version. Implementers who already support /// it should continue to do so for backward compatibility. Implementers should avoid adding new uses of this portion of the /// specification. The specification should include guidance on what implementers should use instead of the deprecated portion /// </summary> [EnumMember(Value = "Deprecated")] Deprecated, } }
55.033333
136
0.687462
[ "Apache-2.0" ]
Kodeistan/nndss-mmg-validator
src/Kodeistan.Mmg/Models/FHIRV4/DevelopmentStatus.cs
3,302
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class CreateAutoSnapshotPolicyResponse : AcsResponse { private string requestId; private string autoSnapshotPolicyId; public string RequestId { get { return requestId; } set { requestId = value; } } public string AutoSnapshotPolicyId { get { return autoSnapshotPolicyId; } set { autoSnapshotPolicyId = value; } } } }
23.561404
63
0.702159
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/CreateAutoSnapshotPolicyResponse.cs
1,343
C#
using System; using System.Windows.Forms; namespace GloWS_Test_App.SOAP { public partial class XMLViewer : Form { private string _textToShow; public XMLViewer(string textToShow) { InitializeComponent(); _textToShow = textToShow; } private void XMLViewer_Load(object sender, EventArgs e) { txtXMLDisplay.Text = _textToShow; txtXMLDisplay.Select(0, 0); } /// <summary> /// Enabled the "Esc" key to close the form (but not affect anything else). /// </summary> /// <param name="keyData"></param> /// <returns></returns> protected override bool ProcessDialogKey(Keys keyData) { if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape) { this.Close(); return true; } return base.ProcessDialogKey(keyData); } } }
25.710526
83
0.541453
[ "MIT" ]
DHL-TarekFadel/GloWS-.NET-Reference-Implementation
GloWS Test App/SOAP/XMLViewer.cs
979
C#
using System.Reflection; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("Models")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Models")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("2d9a668b-4d1a-4fcf-8aa4-c6279b041f77")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // utilizando el carácter "*", como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.833333
112
0.753061
[ "MIT" ]
caidevOficial/CSharp_UTN_LaboII
2_Modelos_Examenes/PP_2021_DepositoElectro/Deposito.Models/Properties/AssemblyInfo.cs
1,488
C#
using System; using System.Linq; using System.Security.Claims; using System.Threading; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.MultiTenancy; using Abp.Runtime.Security; namespace Abp.Runtime.Session { /// <summary> /// Implements <see cref="IAbpSession"/> to get session properties from claims of <see cref="Thread.CurrentPrincipal"/>. /// </summary> public class ClaimsAbpSession : AbpSessionBase, ISingletonDependency { public override long? UserId { get { if (OverridedValue != null) { return OverridedValue.UserId; } var userIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (string.IsNullOrEmpty(userIdClaim?.Value)) { return null; } long userId; if (!long.TryParse(userIdClaim.Value, out userId)) { return null; } return userId; } } public override int? TenantId { get { if (!MultiTenancy.IsEnabled) { return MultiTenancyConsts.DefaultTenantId; } if (OverridedValue != null) { return OverridedValue.TenantId; } var tenantIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.TenantId); if (!string.IsNullOrEmpty(tenantIdClaim?.Value)) { return Convert.ToInt32(tenantIdClaim.Value); } if (UserId == null) { //Resolve tenant id from request only if user has not logged in! return TenantResolver.ResolveTenantId(); } return null; } } public override long? ImpersonatorUserId { get { var impersonatorUserIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorUserId); if (string.IsNullOrEmpty(impersonatorUserIdClaim?.Value)) { return null; } return Convert.ToInt64(impersonatorUserIdClaim.Value); } } public override int? ImpersonatorTenantId { get { if (!MultiTenancy.IsEnabled) { return MultiTenancyConsts.DefaultTenantId; } var impersonatorTenantIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorTenantId); if (string.IsNullOrEmpty(impersonatorTenantIdClaim?.Value)) { return null; } return Convert.ToInt32(impersonatorTenantIdClaim.Value); } } protected IPrincipalAccessor PrincipalAccessor { get; } protected ITenantResolver TenantResolver { get; } public ClaimsAbpSession( IPrincipalAccessor principalAccessor, IMultiTenancyConfig multiTenancy, ITenantResolver tenantResolver, IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider) : base( multiTenancy, sessionOverrideScopeProvider) { TenantResolver = tenantResolver; PrincipalAccessor = principalAccessor; } } }
31.438017
150
0.525762
[ "MIT" ]
UdayaBhandaru/boilerplate
src/Abp/Runtime/Session/ClaimsAbpSession.cs
3,804
C#
using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TimeTracker.Api.Persistence.Core.Models; using Wolf.Utility.Core.Persistence.EntityFramework.Core; namespace TimeTracker.Api.Persistence.Core.EntityFrameworkCore.Config { public class EntryConfig : EntityConfig<Entry> { public EntryConfig() { } public override void Configure(EntityTypeBuilder<Entry> builder) { base.Configure(builder); builder.HasIndex(x => new { x.Name, x.Description }, "UniqueEntryIndex").IsUnique(); builder.HasMany(x => (ICollection<Pause>)x.Pauses).WithOne(x => (Entry)x.Entry).HasForeignKey(x => x.EntryId); builder.Property(x => x.Start).IsRequired(false); builder.Property(x => x.End).IsRequired(false); } } }
29.741935
122
0.677874
[ "MIT" ]
andr9528/TimeTracker
TimeTracker.Api.Persistence.Core/EntityFrameworkCore/Config/EntryConfig.cs
924
C#
using AIStudio.Core; using AIStudio.Core.ExCommand; using AIStudio.Core.Models; using AIStudio.Wpf.BasePage.Events; using AIStudio.Wpf.BasePage.ViewModels; using AIStudio.Wpf.Business; using AIStudio.Wpf.D_Manage.ViewModels; using AIStudio.Wpf.D_Manage.Views; using AIStudio.Wpf.Entity.DTOModels; using AIStudio.Wpf.OA_Manage.ViewModels; using AIStudio.Wpf.OA_Manage.Views; using Newtonsoft.Json; using Prism.Commands; using Prism.Events; using Prism.Ioc; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Input; namespace AIStudio.Wpf.Home.ViewModels { class NoticeIconViewModel : BaseWaitingViewModel { private int _selectedIndex; public int SelectedIndex { get { return _selectedIndex; } set { if (SetProperty(ref _selectedIndex, value)) { GetData(); } } } private ObservableCollection<D_NoticeDTO> _notice; public ObservableCollection<D_NoticeDTO> Notice { get { return _notice; } set { SetProperty(ref _notice, value); } } private ObservableCollection<D_UserMailDTO> _userMail; public ObservableCollection<D_UserMailDTO> UserMail { get { return _userMail; } set { SetProperty(ref _userMail, value); } } private ObservableCollection<GroupData> _userMessage; public ObservableCollection<GroupData> UserMessage { get { return _userMessage; } set { SetProperty(ref _userMessage, value); } } private ObservableCollection<OA_UserFormDTO> _userForm; public ObservableCollection<OA_UserFormDTO> UserForm { get { return _userForm; } set { SetProperty(ref _userForm, value); } } private int _totalCount; /// <summary> /// 总记录数 /// </summary> public int TotalCount { get { return _totalCount; } set { SetProperty(ref _totalCount, value); } } private ICommand _refreshCommand; public ICommand RefreshCommand { get { return this._refreshCommand ?? (this._refreshCommand = new DelegateCommand(() => this.GetData())); } } private ICommand _moreCommand; public ICommand MoreCommand { get { return this._moreCommand ?? (this._moreCommand = new DelegateCommand<string>(para => this.More(para))); } } private ICommand _editCommand; public ICommand EditCommand { get { return this._editCommand ?? (this._editCommand = new DelegateCommand<object>(para => this.Edit(para))); } } public Core.Models.Pagination Notice_Pagination { get; set; } = new Core.Models.Pagination() { PageRows = 5 }; public Core.Models.Pagination UserMail_Pagination { get; set; } = new Core.Models.Pagination() { PageRows = 5 }; public Core.Models.Pagination UserMessage_Pagination { get; set; } = new Core.Models.Pagination() { PageRows = 5 }; public Core.Models.Pagination UserForm_Pagination { get; set; } = new Core.Models.Pagination() { PageRows = 5 }; public string Identifier { get; set; } = LocalSetting.RootWindow; protected IOperator _operator { get => ContainerLocator.Current.Resolve<IOperator>(); } protected IDataProvider _dataProvider { get => ContainerLocator.Current.Resolve<IDataProvider>(); } protected IWSocketClient _wSocketClient { get => ContainerLocator.Current.Resolve<IWSocketClient>(); } protected IUserData _userData { get => ContainerLocator.Current.Resolve<IUserData>(); } protected IEventAggregator _aggregator { get => ContainerLocator.Current.Resolve<IEventAggregator>(); } public NoticeIconViewModel(string identifier) { Identifier = identifier; _wSocketClient.MessageReceived -= _wSocketClient_MessageReceived; _wSocketClient.MessageReceived += _wSocketClient_MessageReceived; } private void _wSocketClient_MessageReceived(WSMessageType type, string message) { if (type == WSMessageType.PushType) { var resmsg = JsonConvert.DeserializeObject<PushMessageData>(message); Notice_Pagination.Total = resmsg.NoticeCount; UserMail_Pagination.Total = resmsg.UserMailCount; UserMessage_Pagination.Total = resmsg.UserMessageCount; UserForm_Pagination.Total = resmsg.UserFormCount; TotalCount = Notice_Pagination.Total + UserMail_Pagination.Total + UserMessage_Pagination.Total + UserForm_Pagination.Total; var clearcache = resmsg.Clearcache; if (clearcache.Contains("Base_User")) { _userData.ClearAllUser(); } if (clearcache.Contains("Base_Role")) { _userData.ClearAllRole(); } } } private async void GetData() { switch (SelectedIndex) { case 0: await GetNotice(); break; case 1: await GetUserMail(); break; case 2: await GetUserMessage(); break; case 3: await GetUserForm(); break; } } private async Task GetNotice() { try { ShowWait(); var data = new { PageIndex = Notice_Pagination.PageIndex, PageRows = Notice_Pagination.PageRows, SortField = Notice_Pagination.SortField, SortType = Notice_Pagination.SortType, Search = new { userId = _operator?.Property?.Id, markflag = true, } }; var result = await _dataProvider.GetData<List<D_NoticeDTO>>($"/D_Manage/D_Notice/GetPageHistoryDataList", JsonConvert.SerializeObject(data)); if (!result.Success) { throw new Exception(result.Msg); } else { Notice_Pagination.Total = result.Total; Notice = new ObservableCollection<D_NoticeDTO>(result.Data); TotalCount = Notice_Pagination.Total + UserMail_Pagination.Total + UserMessage_Pagination.Total + UserForm_Pagination.Total; } } catch (Exception ex) { throw ex; } finally { HideWait(); } } private async Task GetUserMail() { try { ShowWait(); var data = new { PageIndex = UserMail_Pagination.PageIndex, PageRows = UserMail_Pagination.PageRows, SortField = UserMail_Pagination.SortField, SortType = UserMail_Pagination.SortType, Search = new { userId = _operator?.Property?.Id, markflag = true, } }; var result = await _dataProvider.GetData<List<D_UserMailDTO>>($"/D_Manage/D_UserMail/GetPageHistoryDataList", JsonConvert.SerializeObject(data)); if (!result.Success) { throw new Exception(result.Msg); } else { UserMail_Pagination.Total = result.Total; UserMail = new ObservableCollection<D_UserMailDTO>(result.Data); TotalCount = Notice_Pagination.Total + UserMail_Pagination.Total + UserMessage_Pagination.Total + UserForm_Pagination.Total; } } catch (Exception ex) { throw ex; } finally { HideWait(); } } private async Task GetUserMessage() { try { ShowWait(); var data = new { PageIndex = UserMessage_Pagination.PageIndex, PageRows = UserMessage_Pagination.PageRows, SortField = UserMessage_Pagination.SortField, SortType = UserMessage_Pagination.SortType, Search = new { userId = _operator?.Property?.Id, markflag = true, } }; var result = await _dataProvider.GetData<List<GroupData>>($"/D_Manage/D_UserMessage/GetPageHistoryGroupDataList",JsonConvert.SerializeObject(data)); if (!result.Success) { throw new Exception(result.Msg); } else { UserMessage_Pagination.Total = result.Data.Sum(p => p.Total); UserMessage = new ObservableCollection<GroupData>(result.Data); TotalCount = Notice_Pagination.Total + UserMail_Pagination.Total + UserMessage_Pagination.Total + UserForm_Pagination.Total; } } catch (Exception ex) { throw ex; } finally { HideWait(); } } private async Task GetUserForm() { try { ShowWait(); var data = new { PageIndex = UserMessage_Pagination.PageIndex, PageRows = UserMessage_Pagination.PageRows, SortField = UserMessage_Pagination.SortField, SortType = UserMessage_Pagination.SortType, Search = new { userId = _operator?.Property?.Id, } }; var result = await _dataProvider.GetData<List<OA_UserFormDTO>>($"/OA_Manage/OA_UserForm/GetPageHistoryDataList", JsonConvert.SerializeObject(data)); if (!result.Success) { throw new Exception(result.Msg); } else { UserForm_Pagination.Total = result.Total; UserForm = new ObservableCollection<OA_UserFormDTO>(result.Data); TotalCount = Notice_Pagination.Total + UserMail_Pagination.Total + UserMessage_Pagination.Total + UserForm_Pagination.Total; } } catch (Exception ex) { throw ex; } finally { HideWait(); } } private Dictionary<string, string> Dictionary = new Dictionary<string, string>() { { "D_NoticeDTO", typeof(D_NoticeView).FullName }, { "D_UserMailDTO", typeof(D_UserMailIndexView).FullName}, { "D_UserMessageDTO", typeof(D_UserMessageView).FullName}, { "OA_UserFormDTO", typeof(OA_UserFormView).FullName }, }; private void More(string para) { _aggregator.GetEvent<MenuExcuteEvent>().Publish(new Tuple<string, string>(Identifier, Dictionary[para])); } private async void Edit(object para) { var exCommandParameter = para as ExCommandParameter; var obj = (exCommandParameter.Sender as ListBox).SelectedItem; if (obj is D_NoticeDTO) { await D_NoticeViewModel.EditShow(new D_NoticeDTO() { Id = (obj as D_NoticeDTO).Id }, Identifier); } else if (obj is D_UserMailDTO) { await D_UserMailViewModel.EditShow(new D_UserMailDTO() { Id = (obj as D_UserMailDTO).Id }, Identifier); } else if (obj is OA_UserFormDTO) { await OA_UserFormViewModel.EditShow(new OA_UserFormDTO() { Id = (obj as OA_UserFormDTO).Id }, Identifier); } if (obj is GroupData) { GroupData message = obj as GroupData; D_UserMessageViewModel.EditShow(new string[] { message.CreatorId, message.CreatorName, message.Avatar, message.GroupId, message.GroupName, message.UserIds, message.UserNames }); } } } public class PushMessageData { public string[] Clearcache { get; set; } public List<GroupData> UserMessage { get; set; } public int NoticeCount { get; set; } public int UserMessageCount { get; set; } public int UserMailCount { get; set; } public int UserFormCount { get; set; } } public class GroupData { public int Total { get; set; } public string CreatorId { get; set; } public string CreatorName { get; set; } public string Avatar { get; set; } public string GroupId { get; set; } public string GroupName { get; set; } public string UserIds { get; set; } public string UserNames { get; set; } public string Text { get; set; } public DateTime CreateTime { get; set; } } }
34.646192
193
0.531594
[ "MIT" ]
DavosLi0bnip/daranguizu
Page/AIStudio.Wpf.Home/ViewModels/NoticeIconViewModel.cs
14,111
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEngine; namespace Shiningforce { public class Header { public byte Promotion; public List<Texture2D> Textures = new List<Texture2D>(); public ushort ID => toUShort(0); public ushort Width => toUShort(2); public ushort Height => toUShort(4); public byte NumberOfAngles => RawData[0x6]; public byte Junk => RawData[0x7]; public ushort WidthReads => RawData[0x8]; public ushort HeightReads => RawData[0x9]; public byte PromotionSometimes => RawData[0xA]; public byte Junk2 => RawData[0xB]; public uint StartAddress => toUInt(0x10); public uint TimingAddress => toUInt(0x14); protected List<byte> RawData = new List<byte>(); private ushort toUShort(int idx) => (ushort)(RawData[idx] << 8 | RawData[idx + 1]); private uint toUInt(int idx) => (uint)((toUShort(idx) << 16) | toUShort(idx + 2)); public Header(BinaryReader br) { RawData = br.ReadBytes(0x18).ToList(); } } public struct TimingEventFrame { public ushort Index; public ushort NumberOfFrames; public TimingEventFrame(ushort index, ushort fps) { Index = index; NumberOfFrames = fps; } } public class TimingEventFrames { public int this[int animFrame] { get { animFrame %= TotalFrameCount; var frameCount = 0; foreach (var e in Events) { if (animFrame - frameCount < e.NumberOfFrames) { return e.Index; } frameCount += e.NumberOfFrames; } return Events.Last().Index; } } public int TotalFrameCount => Events.Sum(s => s.NumberOfFrames); public List<TimingEventFrame> Events = new List<TimingEventFrame>(); public void Add(TimingEventFrame timingEvent) => Events.Add(timingEvent); } public struct SpriteLayout { public int X; public int Y; public int Width; public int Height; public int NumOfFrames; } public enum Direction { DOWN_RIGHT_HARD, DOWN_RIGHT_EASY, UP_RIGHT_EASY, UP_RIGHT_HARD, DOWN, UP } public enum AnimationState { STATIONARY, IDLE, WALK, YES, NO, SPELLSTATIONARY, SPELL, KNEELINGSTATIONARY, KNEELING, GETTINGUP, STATE10, STATE11, STATE12, STATE13, STATE14, STATE15, } public class SpriteSheet { public Header Header; public uint TimingAddress => Header.TimingAddress; public int ID => Header.ID; public List<uint> Frames = new List<uint>(); public Texture2D TextureAtlas; public bool Active => Header.NumberOfAngles == 6; public int Promotion => Header.Promotion; public int CurrentFrame = 0; private AnimationState _State = AnimationState.STATIONARY; public AnimationState State { get => _State; set { if (_State == value) return; if (TimingEvents.Count <= (int)value) { value = AnimationState.STATIONARY; } _State = value; CurrentFrame = 0; } } private List<Sprite> SpriteCollection = new List<Sprite>(); public List<TimingEventFrames> TimingEvents = new List<TimingEventFrames>(); //public SpriteSheet this[int i] => SpriteCollection.FirstOrDefault(s => s.ID == i && s.Active == false && s.Promotion == 0); //public SpriteSheet this[int i, bool active] => SpriteCollection.FirstOrDefault(s => s.ID == i && s.Active == active && s.Promotion == 0); //public SpriteSheet this[int i, int promotion] => SpriteCollection.FirstOrDefault(s => s.ID == i && s.Active == false && s.Promotion == promotion); public Sprite this[int frame, int rotation] => SpriteCollection[TimingEvents[(int)State][frame] + rotation]; public SpriteSheet(BinaryReader br) { Header = new Header(br); } public uint ExtractFrames(BinaryReader br, long StartingPosition) { var read = 0xFFFFFFFF; br.Position(StartingPosition + Header.StartAddress); while (read > 0) { read = br.ReadUInt32().FlipEndian(); if (read != 0) Frames.Add(read); } return read; } public void ExtractTiming(BinaryReader br, long StartingPosition) { var timingEventAddresses = new List<uint>(); var lengthTimingEventAddresses = new List<uint>(); br.Position(StartingPosition + Header.TimingAddress); var read = 0xFFFFFFFF; for (int i = 0; i < 16; i++) { read = br.ReadUInt32().FlipEndian(); if (timingEventAddresses.Count > 0) { lengthTimingEventAddresses.Add(read); } timingEventAddresses.Add(read); } lengthTimingEventAddresses.Reverse(); lengthTimingEventAddresses = lengthTimingEventAddresses.SkipWhile(s => s == 0).ToList(); lengthTimingEventAddresses.Reverse(); lengthTimingEventAddresses.Add(Header.TimingAddress); for (var t = 0; t < timingEventAddresses.Count; t++) { var timingEvents = new TimingEventFrames(); if (timingEventAddresses[t] == 0) { TimingEvents.Add(timingEvents); continue; } br.Position(StartingPosition + timingEventAddresses[t]); while (br.Position() < StartingPosition + lengthTimingEventAddresses[t]) { var index = (ushort)(br.ReadUInt16().FlipEndian()); var frames = br.ReadUInt16().FlipEndian(); var timingEvent = new TimingEventFrame(index, frames); timingEvents.Add(timingEvent); if ((sbyte)index < 0) break; } TimingEvents.Add(timingEvents); } } public void DecompressImages(BinaryReader br, long StartingPosition, ref long EndingPosition) { Texture2D texture = CreateSheet(br, StartingPosition, ref EndingPosition); TextureAtlas = texture; var imageCount = (int)Math.Ceiling((double)Header.Textures.Count / Header.NumberOfAngles) * Header.NumberOfAngles; for (int sX = 0; sX < imageCount; sX++) { var sprite = Sprite.Create(texture, new Rect(sX * Header.Width, 0, Header.Width, Header.Height), new Vector2(0.5f, 0.5f), 100f); SpriteCollection.Add(sprite); } } public Texture2D CreateSheet(BinaryReader br, long StartingPosition, ref long EndingPosition) { Header.Textures = new List<Texture2D>(); var frames = Frames; for (int f = 0; f < frames.Count; f++) { try { var frame = frames[f]; br.Position(StartingPosition + frame); var test = RawImageDecoder.DecompressImage(br).ToArray(); Header.Textures.Add(test.ToTexture2D(Header.Width, Header.Height)); EndingPosition = Math.Max(EndingPosition, br.Position()); } catch (Exception ex) { ex.ToString(); } } var imageCount = (int)Math.Ceiling((double)Header.Textures.Count / Header.NumberOfAngles) * Header.NumberOfAngles; var sheet = new Texture2D(Header.Width * imageCount, Header.Height); sheet.filterMode = FilterMode.Point; var x = 0; for (var i = 0; i < Header.Textures.Count; i++) { for (var ty = 0; ty < Header.Height; ty++) { for (var tx = 0; tx < Header.Width; tx++) { sheet.SetPixel(x + tx, (Header.Height - 1) - ty, Header.Textures[i].GetPixel(tx, ty)); } } x += Header.Width; } sheet.Apply(); return sheet; } public void Export(string name) => File.WriteAllBytes(Path.Combine(Directory.GetCurrentDirectory(), $"{name}.png"), TextureAtlas.EncodeToPNG()); } }
34.63197
157
0.517497
[ "MIT" ]
AndreasScholl/SF3Unity
Assets/Scripts/SF3/Sprites/SpriteSheet.cs
9,318
C#
using System; using System.Threading.Tasks; using Baseline; using Jasper.Runtime; using Polly; namespace Jasper.ErrorHandling { public static class JasperPollyExtensions { public const string ContextKey = "context"; internal static IAsyncPolicy<IContinuation> Requeue(this PolicyBuilder<IContinuation> builder, int maxAttempts = 3) { return builder.FallbackAsync((result, context, token) => { var envelope = context.MessageContext().Envelope; var continuation = envelope.Attempts < maxAttempts ? (IContinuation) RequeueContinuation.Instance : new MoveToErrorQueue(result.Exception); return Task.FromResult(continuation); }, (result, context) => Task.CompletedTask); } internal static void Store(this Context context, IMessageContext messageContext) { context.Add(ContextKey, messageContext); } internal static IMessageContext MessageContext(this Context context) { return context[ContextKey].As<IMessageContext>(); } /// <summary> /// Specifies the type of exception that this policy can handle. /// </summary> /// <typeparam name="TException">The type of the exception to handle.</typeparam> /// <returns>The PolicyBuilder instance.</returns> public static PolicyExpression OnException<TException>(this IHasRetryPolicies policies) where TException : Exception { var builder = Policy<IContinuation>.Handle<TException>(); return new PolicyExpression(policies.Retries, builder); } /// <summary> /// Specifies the type of exception that this policy can handle with additional filters on this exception type. /// </summary> /// <typeparam name="TException">The type of the exception.</typeparam> /// <param name="policies"></param> /// <param name="exceptionPredicate">The exception predicate to filter the type of exception this policy can handle.</param> /// <returns>The PolicyBuilder instance.</returns> public static PolicyExpression OnException(this IHasRetryPolicies policies, Func<Exception, bool> exceptionPredicate) { var builder = Policy<IContinuation>.Handle(exceptionPredicate); return new PolicyExpression(policies.Retries, builder); } /// <summary> /// Specifies the type of exception that this policy can handle with additional filters on this exception type. /// </summary> /// <param name="policies"></param> /// <param name="exceptionType">An exception type to match against</param> /// <returns>The PolicyBuilder instance.</returns> public static PolicyExpression OnExceptionOfType(this IHasRetryPolicies policies, Type exceptionType) { return policies.OnException(e => e.GetType().CanBeCastTo(exceptionType)); } /// <summary> /// Specifies the type of exception that this policy can handle with additional filters on this exception type. /// </summary> /// <typeparam name="TException">The type of the exception.</typeparam> /// <param name="policies"></param> /// <param name="exceptionPredicate">The exception predicate to filter the type of exception this policy can handle.</param> /// <returns>The PolicyBuilder instance.</returns> public static PolicyExpression OnException<TException>(this IHasRetryPolicies policies, Func<TException, bool> exceptionPredicate) where TException : Exception { var builder = Policy<IContinuation>.Handle(exceptionPredicate); return new PolicyExpression(policies.Retries, builder); } /// <summary> /// Specifies the type of exception that this policy can handle if found as an InnerException of a regular /// <see cref="Exception" />, or at any level of nesting within an <see cref="AggregateException" />. /// </summary> /// <typeparam name="TException">The type of the exception to handle.</typeparam> /// <returns>The PolicyBuilder instance, for fluent chaining.</returns> public static PolicyExpression HandleInner<TException>(this IHasRetryPolicies policies) where TException : Exception { var builder = Policy<IContinuation>.HandleInner<TException>(); return new PolicyExpression(policies.Retries, builder); } /// <summary> /// Specifies the type of exception that this policy can handle, with additional filters on this exception type, if /// found as an InnerException of a regular <see cref="Exception" />, or at any level of nesting within an /// <see cref="AggregateException" />. /// </summary> /// <typeparam name="TException">The type of the exception to handle.</typeparam> /// <returns>The PolicyBuilder instance, for fluent chaining.</returns> public static PolicyExpression HandleInner<TException>(this IHasRetryPolicies policies, Func<TException, bool> exceptionPredicate) where TException : Exception { var builder = Policy<IContinuation>.HandleInner(exceptionPredicate); return new PolicyExpression(policies.Retries, builder); } } }
45.520661
138
0.651961
[ "MIT" ]
CodingGorilla/jasper
src/Jasper/ErrorHandling/PollyUsage.cs
5,508
C#
using ICSharpCode.NRefactory.CSharp.Refactoring; using NUnit.Framework; namespace ICSharpCode.NRefactory.CSharp.CodeActions { [TestFixture] class InvertIfAndSimplifyTests : ContextActionTestBase { [Test] public void Test() { Test<InvertIfAndSimplify>( @"class TestClass { void Test () { $if (true) { Case1 (); Case2 (); } else { return; } } }", @"class TestClass { void Test () { if (false) return; Case1 (); Case2 (); } }" ); } [Test] public void TestNonVoidMoreComplexMethod() { Test<InvertIfAndSimplify>( @"class TestClass { int Test () { $if (true) { Case1 (); } else { return 0; testDummyCode (); } } }", @"class TestClass { int Test () { if (false) { return 0; testDummyCode (); } Case1 (); } }" ); } [Test] public void TestComplexMethod() { Test<InvertIfAndSimplify>( @"class TestClass { int Test () { $if (true) { Case1 (); } else continue; return 0; } }", @"class TestClass { int Test () { if (false) continue; Case1 (); return 0; } }" ); } [Test] public void TestComment() { Test<InvertIfAndSimplify>( @"class TestClass { int Test () { $if (true) { Case1 (); } else { //TestComment return 0; } } }", @"class TestClass { int Test () { if (false) { //TestComment return 0; } Case1 (); } }" ); } } }
11.014706
55
0.523364
[ "MIT" ]
Jenkin0603/myvim
bundle/omnisharp-vim/server/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/InvertIfAndSimplifyTests.cs
1,498
C#
using System; using System.Collections.Concurrent; namespace YouiToolkit.Logging { /// <summary> /// 线程安全队列 /// </summary> /// <typeparam name="T">数据类型</typeparam> public class ConcurrentQueueEx<T> : ConcurrentQueue<T> { /// <summary> /// 清除数据 /// </summary> /// <returns>清除个数</returns> public int Clear() { int cleanCount = default; int commandCount = Count; if (commandCount > 0) { for (int i = default; i < commandCount; i++) { if (Count > 0) { try { if (TryDequeue(out T _)) { cleanCount++; } } catch (Exception e) { Logger.Warn(e.ToString()); } } } } return cleanCount; } } }
25.244444
60
0.337148
[ "Unlicense" ]
MaQaQu/Tool
YouiToolkit.Logging/Logger/Threadings/ConcurrentQueueEx.cs
1,174
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MIGAZ.Generator { public interface ITelemetryProvider { void PostTelemetryRecord(string AccessKey, Dictionary<string, string> processedItems, string Region); } }
22.611111
109
0.761671
[ "MIT" ]
Azure/migAz
aws/source/MIGAZ/Generator/ITelemetryProvider.cs
407
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; using Azure.ResourceManager; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { public partial class VpnConnectionData : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Name)) { writer.WritePropertyName("name"); writer.WriteStringValue(Name); } writer.WritePropertyName("id"); writer.WriteStringValue(Id); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(RemoteVpnSite)) { writer.WritePropertyName("remoteVpnSite"); writer.WriteObjectValue(RemoteVpnSite); } if (Optional.IsDefined(RoutingWeight)) { writer.WritePropertyName("routingWeight"); writer.WriteNumberValue(RoutingWeight.Value); } if (Optional.IsDefined(DpdTimeoutSeconds)) { writer.WritePropertyName("dpdTimeoutSeconds"); writer.WriteNumberValue(DpdTimeoutSeconds.Value); } if (Optional.IsDefined(VpnConnectionProtocolType)) { writer.WritePropertyName("vpnConnectionProtocolType"); writer.WriteStringValue(VpnConnectionProtocolType.Value.ToString()); } if (Optional.IsDefined(ConnectionBandwidth)) { writer.WritePropertyName("connectionBandwidth"); writer.WriteNumberValue(ConnectionBandwidth.Value); } if (Optional.IsDefined(SharedKey)) { writer.WritePropertyName("sharedKey"); writer.WriteStringValue(SharedKey); } if (Optional.IsDefined(EnableBgp)) { writer.WritePropertyName("enableBgp"); writer.WriteBooleanValue(EnableBgp.Value); } if (Optional.IsDefined(UsePolicyBasedTrafficSelectors)) { writer.WritePropertyName("usePolicyBasedTrafficSelectors"); writer.WriteBooleanValue(UsePolicyBasedTrafficSelectors.Value); } if (Optional.IsCollectionDefined(IpsecPolicies)) { writer.WritePropertyName("ipsecPolicies"); writer.WriteStartArray(); foreach (var item in IpsecPolicies) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(TrafficSelectorPolicies)) { writer.WritePropertyName("trafficSelectorPolicies"); writer.WriteStartArray(); foreach (var item in TrafficSelectorPolicies) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(EnableRateLimiting)) { writer.WritePropertyName("enableRateLimiting"); writer.WriteBooleanValue(EnableRateLimiting.Value); } if (Optional.IsDefined(EnableInternetSecurity)) { writer.WritePropertyName("enableInternetSecurity"); writer.WriteBooleanValue(EnableInternetSecurity.Value); } if (Optional.IsDefined(UseLocalAzureIpAddress)) { writer.WritePropertyName("useLocalAzureIpAddress"); writer.WriteBooleanValue(UseLocalAzureIpAddress.Value); } if (Optional.IsCollectionDefined(VpnLinkConnections)) { writer.WritePropertyName("vpnLinkConnections"); writer.WriteStartArray(); foreach (var item in VpnLinkConnections) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(RoutingConfiguration)) { writer.WritePropertyName("routingConfiguration"); writer.WriteObjectValue(RoutingConfiguration); } writer.WriteEndObject(); writer.WriteEndObject(); } internal static VpnConnectionData DeserializeVpnConnectionData(JsonElement element) { Optional<string> name = default; Optional<string> etag = default; ResourceIdentifier id = default; Optional<SubResource> remoteVpnSite = default; Optional<int> routingWeight = default; Optional<int> dpdTimeoutSeconds = default; Optional<VpnConnectionStatus> connectionStatus = default; Optional<VirtualNetworkGatewayConnectionProtocol> vpnConnectionProtocolType = default; Optional<long> ingressBytesTransferred = default; Optional<long> egressBytesTransferred = default; Optional<int> connectionBandwidth = default; Optional<string> sharedKey = default; Optional<bool> enableBgp = default; Optional<bool> usePolicyBasedTrafficSelectors = default; Optional<IList<IpsecPolicy>> ipsecPolicies = default; Optional<IList<TrafficSelectorPolicy>> trafficSelectorPolicies = default; Optional<bool> enableRateLimiting = default; Optional<bool> enableInternetSecurity = default; Optional<bool> useLocalAzureIpAddress = default; Optional<ProvisioningState> provisioningState = default; Optional<IList<VpnSiteLinkConnection>> vpnLinkConnections = default; Optional<RoutingConfiguration> routingConfiguration = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("etag")) { etag = property.Value.GetString(); continue; } if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("remoteVpnSite")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } remoteVpnSite = SubResource.DeserializeSubResource(property0.Value); continue; } if (property0.NameEquals("routingWeight")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } routingWeight = property0.Value.GetInt32(); continue; } if (property0.NameEquals("dpdTimeoutSeconds")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } dpdTimeoutSeconds = property0.Value.GetInt32(); continue; } if (property0.NameEquals("connectionStatus")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } connectionStatus = new VpnConnectionStatus(property0.Value.GetString()); continue; } if (property0.NameEquals("vpnConnectionProtocolType")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } vpnConnectionProtocolType = new VirtualNetworkGatewayConnectionProtocol(property0.Value.GetString()); continue; } if (property0.NameEquals("ingressBytesTransferred")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } ingressBytesTransferred = property0.Value.GetInt64(); continue; } if (property0.NameEquals("egressBytesTransferred")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } egressBytesTransferred = property0.Value.GetInt64(); continue; } if (property0.NameEquals("connectionBandwidth")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } connectionBandwidth = property0.Value.GetInt32(); continue; } if (property0.NameEquals("sharedKey")) { sharedKey = property0.Value.GetString(); continue; } if (property0.NameEquals("enableBgp")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } enableBgp = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("usePolicyBasedTrafficSelectors")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } usePolicyBasedTrafficSelectors = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("ipsecPolicies")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List<IpsecPolicy> array = new List<IpsecPolicy>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(IpsecPolicy.DeserializeIpsecPolicy(item)); } ipsecPolicies = array; continue; } if (property0.NameEquals("trafficSelectorPolicies")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List<TrafficSelectorPolicy> array = new List<TrafficSelectorPolicy>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(TrafficSelectorPolicy.DeserializeTrafficSelectorPolicy(item)); } trafficSelectorPolicies = array; continue; } if (property0.NameEquals("enableRateLimiting")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } enableRateLimiting = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("enableInternetSecurity")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } enableInternetSecurity = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("useLocalAzureIpAddress")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } useLocalAzureIpAddress = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("provisioningState")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } provisioningState = new ProvisioningState(property0.Value.GetString()); continue; } if (property0.NameEquals("vpnLinkConnections")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List<VpnSiteLinkConnection> array = new List<VpnSiteLinkConnection>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(VpnSiteLinkConnection.DeserializeVpnSiteLinkConnection(item)); } vpnLinkConnections = array; continue; } if (property0.NameEquals("routingConfiguration")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } routingConfiguration = RoutingConfiguration.DeserializeRoutingConfiguration(property0.Value); continue; } } continue; } } return new VpnConnectionData(id, name.Value, etag.Value, remoteVpnSite.Value, Optional.ToNullable(routingWeight), Optional.ToNullable(dpdTimeoutSeconds), Optional.ToNullable(connectionStatus), Optional.ToNullable(vpnConnectionProtocolType), Optional.ToNullable(ingressBytesTransferred), Optional.ToNullable(egressBytesTransferred), Optional.ToNullable(connectionBandwidth), sharedKey.Value, Optional.ToNullable(enableBgp), Optional.ToNullable(usePolicyBasedTrafficSelectors), Optional.ToList(ipsecPolicies), Optional.ToList(trafficSelectorPolicies), Optional.ToNullable(enableRateLimiting), Optional.ToNullable(enableInternetSecurity), Optional.ToNullable(useLocalAzureIpAddress), Optional.ToNullable(provisioningState), Optional.ToList(vpnLinkConnections), routingConfiguration.Value); } } }
48.057592
798
0.46699
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/VpnConnectionData.Serialization.cs
18,358
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.AccessAnalyzer; using Amazon.AccessAnalyzer.Model; namespace Amazon.PowerShell.Cmdlets.IAMAA { /// <summary> /// Creates an analyzer for your account. /// </summary> [Cmdlet("New", "IAMAAAnalyzer", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("System.String")] [AWSCmdlet("Calls the AWS IAM Access Analyzer CreateAnalyzer API operation.", Operation = new[] {"CreateAnalyzer"}, SelectReturnType = typeof(Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse))] [AWSCmdletOutput("System.String or Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class NewIAMAAAnalyzerCmdlet : AmazonAccessAnalyzerClientCmdlet, IExecutor { #region Parameter AnalyzerName /// <summary> /// <para> /// <para>The name of the analyzer to create.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AnalyzerName { get; set; } #endregion #region Parameter ArchiveRule /// <summary> /// <para> /// <para>Specifies the archive rules to add for the analyzer. Archive rules automatically archive /// findings that meet the criteria you define for the rule.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("ArchiveRules")] public Amazon.AccessAnalyzer.Model.InlineArchiveRule[] ArchiveRule { get; set; } #endregion #region Parameter Tag /// <summary> /// <para> /// <para>The tags to apply to the analyzer.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Tags")] public System.Collections.Hashtable Tag { get; set; } #endregion #region Parameter Type /// <summary> /// <para> /// <para>The type of analyzer to create. Only ACCOUNT analyzers are supported. You can create /// only one analyzer per account per Region.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [AWSConstantClassSource("Amazon.AccessAnalyzer.Type")] public Amazon.AccessAnalyzer.Type Type { get; set; } #endregion #region Parameter ClientToken /// <summary> /// <para> /// <para>A client token.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Arn'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse). /// Specifying the name of a property of type Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "Arn"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the AnalyzerName parameter. /// The -PassThru parameter is deprecated, use -Select '^AnalyzerName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^AnalyzerName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.AnalyzerName), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-IAMAAAnalyzer (CreateAnalyzer)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse, NewIAMAAAnalyzerCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.AnalyzerName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AnalyzerName = this.AnalyzerName; #if MODULAR if (this.AnalyzerName == null && ParameterWasBound(nameof(this.AnalyzerName))) { WriteWarning("You are passing $null as a value for parameter AnalyzerName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.ArchiveRule != null) { context.ArchiveRule = new List<Amazon.AccessAnalyzer.Model.InlineArchiveRule>(this.ArchiveRule); } context.ClientToken = this.ClientToken; if (this.Tag != null) { context.Tag = new Dictionary<System.String, System.String>(StringComparer.Ordinal); foreach (var hashKey in this.Tag.Keys) { context.Tag.Add((String)hashKey, (String)(this.Tag[hashKey])); } } context.Type = this.Type; #if MODULAR if (this.Type == null && ParameterWasBound(nameof(this.Type))) { WriteWarning("You are passing $null as a value for parameter Type which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.AccessAnalyzer.Model.CreateAnalyzerRequest(); if (cmdletContext.AnalyzerName != null) { request.AnalyzerName = cmdletContext.AnalyzerName; } if (cmdletContext.ArchiveRule != null) { request.ArchiveRules = cmdletContext.ArchiveRule; } if (cmdletContext.ClientToken != null) { request.ClientToken = cmdletContext.ClientToken; } if (cmdletContext.Tag != null) { request.Tags = cmdletContext.Tag; } if (cmdletContext.Type != null) { request.Type = cmdletContext.Type; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse CallAWSServiceOperation(IAmazonAccessAnalyzer client, Amazon.AccessAnalyzer.Model.CreateAnalyzerRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS IAM Access Analyzer", "CreateAnalyzer"); try { #if DESKTOP return client.CreateAnalyzer(request); #elif CORECLR return client.CreateAnalyzerAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AnalyzerName { get; set; } public List<Amazon.AccessAnalyzer.Model.InlineArchiveRule> ArchiveRule { get; set; } public System.String ClientToken { get; set; } public Dictionary<System.String, System.String> Tag { get; set; } public Amazon.AccessAnalyzer.Type Type { get; set; } public System.Func<Amazon.AccessAnalyzer.Model.CreateAnalyzerResponse, NewIAMAAAnalyzerCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Arn; } } }
44.364821
283
0.602496
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/AccessAnalyzer/Basic/New-IAMAAAnalyzer-Cmdlet.cs
13,620
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SimpleLoginForm.Models; namespace SimpleLoginForm.Migrations { [DbContext(typeof(DatabaseContext))] partial class DatabaseContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.11-servicing-32099") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("SimpleLoginForm.Models.AccountModel", b => { b.Property<int>("id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("accountCreation"); b.Property<string>("approvedAddress"); b.Property<string>("email"); b.Property<string>("password"); b.Property<string>("username"); b.HasKey("id"); b.ToTable("accountsTable"); }); #pragma warning restore 612, 618 } } }
34.288889
125
0.624757
[ "MIT" ]
griffinpuc/stock-usermodel
Migrations/DatabaseContextModelSnapshot.cs
1,545
C#
using System; using System.Linq; using UnityEngine; namespace UnityEditor.Rendering.LWRP { // This is to keep the namespace UnityEditor.Rendering.LWRP alive, // so that user scripts that have "using UnityEditor.Rendering.LWRP" in them still compile. internal class Deprecated { } } namespace UnityEditor.Rendering.Universal { static partial class EditorUtils { [Obsolete("This is obsolete, please use DrawCascadeSplitGUI<T>(ref SerializedProperty shadowCascadeSplit, float distance, int cascadeCount, Unit unit) instead.", false)] public static void DrawCascadeSplitGUI<T>(ref SerializedProperty shadowCascadeSplit) { float[] cascadePartitionSizes = null; Type type = typeof(T); if (type == typeof(float)) { cascadePartitionSizes = new float[] { shadowCascadeSplit.floatValue }; } else if (type == typeof(Vector3)) { Vector3 splits = shadowCascadeSplit.vector3Value; cascadePartitionSizes = new float[] { Mathf.Clamp(splits[0], 0.0f, 1.0f), Mathf.Clamp(splits[1] - splits[0], 0.0f, 1.0f), Mathf.Clamp(splits[2] - splits[1], 0.0f, 1.0f) }; } if (cascadePartitionSizes != null) { EditorGUI.BeginChangeCheck(); ShadowCascadeSplitGUI.HandleCascadeSliderGUI(ref cascadePartitionSizes); if (EditorGUI.EndChangeCheck()) { if (type == typeof(float)) shadowCascadeSplit.floatValue = cascadePartitionSizes[0]; else { Vector3 updatedValue = new Vector3(); updatedValue[0] = cascadePartitionSizes[0]; updatedValue[1] = updatedValue[0] + cascadePartitionSizes[1]; updatedValue[2] = updatedValue[1] + cascadePartitionSizes[2]; shadowCascadeSplit.vector3Value = updatedValue; } } } } } static partial class ShadowCascadeSplitGUI { [Obsolete("This is obsolete, please use HandleCascadeSliderGUI(ref float[] normalizedCascadePartitions, float distance, EditorUtils.Unit unit) instead.", false)] public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartitions) { EditorGUILayout.BeginHorizontal(); GUILayout.Space(EditorGUI.indentLevel * 15f); // get the inspector width since we need it while drawing the partition rects. // Only way currently is to reserve the block in the layout using GetRect(), and then immediately drawing the empty box // to match the call to GetRect. // From this point on, we move to non-layout based code. var sliderRect = GUILayoutUtility.GetRect(GUIContent.none , s_CascadeSliderBG , GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin) , GUILayout.ExpandWidth(true)); GUI.Box(sliderRect, GUIContent.none); EditorGUILayout.EndHorizontal(); float currentX = sliderRect.x; float cascadeBoxStartY = sliderRect.y + kSliderbarTopMargin; float cascadeSliderWidth = sliderRect.width - (normalizedCascadePartitions.Length * kPartitionHandleWidth); Color origTextColor = GUI.color; Color origBackgroundColor = GUI.backgroundColor; int colorIndex = -1; // setup the array locally with the last partition float[] adjustedCascadePartitions = new float[normalizedCascadePartitions.Length + 1]; System.Array.Copy(normalizedCascadePartitions, adjustedCascadePartitions, normalizedCascadePartitions.Length); adjustedCascadePartitions[adjustedCascadePartitions.Length - 1] = 1.0f - normalizedCascadePartitions.Sum(); // check for user input on any of the partition handles // this mechanism gets the current event in the queue... make sure that the mouse is over our control before consuming the event int sliderControlId = GUIUtility.GetControlID(s_CascadeSliderId, FocusType.Passive); Event currentEvent = Event.current; int hotPartitionHandleIndex = -1; // the index of any partition handle that we are hovering over or dragging // draw each cascade partition for (int i = 0; i < adjustedCascadePartitions.Length; ++i) { float currentPartition = adjustedCascadePartitions[i]; colorIndex = (colorIndex + 1) % kCascadeColors.Length; GUI.backgroundColor = kCascadeColors[colorIndex]; float boxLength = (cascadeSliderWidth * currentPartition); // main cascade box Rect partitionRect = new Rect(currentX, cascadeBoxStartY, boxLength, kSliderbarHeight); GUI.Box(partitionRect, GUIContent.none, s_CascadeSliderBG); currentX += boxLength; // cascade box percentage text GUI.color = Color.white; Rect textRect = partitionRect; var cascadeText = string.Format("{0}\n{1:F1}%", i, currentPartition * 100.0f); GUI.Label(textRect, cascadeText, s_TextCenteredStyle); // no need to draw the partition handle for last box if (i == adjustedCascadePartitions.Length - 1) break; // partition handle GUI.backgroundColor = Color.black; Rect handleRect = partitionRect; handleRect.x = currentX; handleRect.width = kPartitionHandleWidth; GUI.Box(handleRect, GUIContent.none, s_CascadeSliderBG); // we want a thin handle visually (since wide black bar looks bad), but a slightly larger // hit area for easier manipulation Rect handleHitRect = handleRect; handleHitRect.xMin -= kPartitionHandleExtraHitAreaWidth; handleHitRect.xMax += kPartitionHandleExtraHitAreaWidth; if (handleHitRect.Contains(currentEvent.mousePosition)) hotPartitionHandleIndex = i; // add regions to slider where the cursor changes to Resize-Horizontal if (s_DragCache == null) { EditorGUIUtility.AddCursorRect(handleHitRect, MouseCursor.ResizeHorizontal, sliderControlId); } currentX += kPartitionHandleWidth; } GUI.color = origTextColor; GUI.backgroundColor = origBackgroundColor; EventType eventType = currentEvent.GetTypeForControl(sliderControlId); switch (eventType) { case EventType.MouseDown: if (hotPartitionHandleIndex >= 0) { s_DragCache = new DragCache(hotPartitionHandleIndex, normalizedCascadePartitions[hotPartitionHandleIndex], currentEvent.mousePosition); if (GUIUtility.hotControl == 0) GUIUtility.hotControl = sliderControlId; currentEvent.Use(); // Switch active scene view into shadow cascades visualization mode, once we start // tweaking cascade splits. if (s_RestoreSceneView == null) { s_RestoreSceneView = SceneView.lastActiveSceneView; if (s_RestoreSceneView != null) { s_OldSceneDrawMode = s_RestoreSceneView.cameraMode; #if UNITY_2019_1_OR_NEWER s_OldSceneLightingMode = s_RestoreSceneView.sceneLighting; #else s_OldSceneLightingMode = s_RestoreSceneView.m_SceneLighting; #endif s_RestoreSceneView.cameraMode = SceneView.GetBuiltinCameraMode(DrawCameraMode.ShadowCascades); } } } break; case EventType.MouseUp: // mouseUp event anywhere should release the hotcontrol (if it belongs to us), drags (if any) if (GUIUtility.hotControl == sliderControlId) { GUIUtility.hotControl = 0; currentEvent.Use(); } s_DragCache = null; // Restore previous scene view drawing mode once we stop tweaking cascade splits. if (s_RestoreSceneView != null) { s_RestoreSceneView.cameraMode = s_OldSceneDrawMode; #if UNITY_2019_1_OR_NEWER s_RestoreSceneView.sceneLighting = s_OldSceneLightingMode; #else s_RestoreSceneView.m_SceneLighting = s_OldSceneLightingMode; #endif s_RestoreSceneView = null; } break; case EventType.MouseDrag: if (GUIUtility.hotControl != sliderControlId) break; // convert the mouse movement to normalized cascade width. Make sure that we are safe to apply the delta before using it. float delta = (currentEvent.mousePosition - s_DragCache.m_LastCachedMousePosition).x / cascadeSliderWidth; bool isLeftPartitionHappy = ((adjustedCascadePartitions[s_DragCache.m_ActivePartition] + delta) > 0.0f); bool isRightPartitionHappy = ((adjustedCascadePartitions[s_DragCache.m_ActivePartition + 1] - delta) > 0.0f); if (isLeftPartitionHappy && isRightPartitionHappy) { s_DragCache.m_NormalizedPartitionSize += delta; normalizedCascadePartitions[s_DragCache.m_ActivePartition] = s_DragCache.m_NormalizedPartitionSize; if (s_DragCache.m_ActivePartition < normalizedCascadePartitions.Length - 1) normalizedCascadePartitions[s_DragCache.m_ActivePartition + 1] -= delta; GUI.changed = true; } s_DragCache.m_LastCachedMousePosition = currentEvent.mousePosition; currentEvent.Use(); break; } } } }
48.878378
177
0.579025
[ "Apache-2.0" ]
AJTheEnder/E428
Projet/E428/Library/PackageCache/com.unity.render-pipelines.universal@10.4.0/Editor/Deprecated.cs
10,851
C#
#region "copyright" /* Copyright © 2016 - 2021 Stefan Berg <isbeorn86+NINA@googlemail.com> and the N.I.N.A. contributors This file is part of N.I.N.A. - Nighttime Imaging 'N' Astronomy. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #endregion "copyright" using FluentAssertions; using FTD2XX_NET; using Moq; using NINA.MGEN; using NINA.MGEN2.Commands.AppMode; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace NINATest.MGEN.Commands { [TestFixture] public class GetLEDStatesCommandTest : CommandTestRunner { private Mock<IFTDI> ftdiMock = new Mock<IFTDI>(); [Test] public void ConstructorTest() { var sut = new GetLEDStatesCommand(); sut.CommandCode.Should().Be(0x5d); sut.AcknowledgeCode.Should().Be(0x5d); sut.SubCommandCode.Should().Be(0x0a); sut.RequiredBaudRate.Should().Be(250000); sut.Timeout.Should().Be(1000); } [Test] [TestCase(LEDS.BLUE | LEDS.DOWN_RED)] [TestCase(LEDS.UP_RED | LEDS.GREEN | LEDS.RIGHT_RED)] [TestCase(LEDS.UP_RED)] public void Successful_Scenario_Test(LEDS expectedLEDs) { SetupWrite(ftdiMock, new byte[] { 0x5d }, new byte[] { 0x0a }, new byte[] { 1 }); SetupRead(ftdiMock, new byte[] { 0x5d }, new byte[] { (byte)expectedLEDs }); var sut = new GetLEDStatesCommand(); var result = sut.Execute(ftdiMock.Object); result.Success.Should().BeTrue(); result.LEDs.Should().Be(expectedLEDs); } } }
30.52459
101
0.643931
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
daleghent/NINA
NINATest/MGEN/Commands/GetLEDStatesCommandTest.cs
1,863
C#
// // Copyright 2017, Zühlke // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Http; using Services.Interfaces; using Services.Services; using WhiteBoardDetection; namespace SharedWhiteBoard.Controllers { public class ImageController : ApiController { private readonly ISessionService _sessionService; public ImageController() { _sessionService = new SessionService(); } [HttpPost] [Route("ImageApi/Session/{sessionPin:long}/Image/{participantOrder}")] public async Task<IHttpActionResult> UploadImage(long sessionPin, string participantOrder) { if (!SessionIsValid(sessionPin)) { return BadRequest(Resources.Resources.NoSessionWithTheGivenPin); } try { var image = await Request.Content.ReadAsByteArrayAsync(); var storageFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}\\{Resources.Resources.StorageFolder}"; var participantStorageFolderPath = $"{storageFolderPath}\\{sessionPin}\\{participantOrder}"; var inputDirectoryFullPath = $"{participantStorageFolderPath}\\{Resources.Resources.InputFolder}\\image.jpg"; System.IO.File.WriteAllBytes(inputDirectoryFullPath, image); // TODO Use IoC var imageRotator = new ImageRotator(); var whiteBoardExtractor = new WhiteBoardExtractor( new CornerFinderAccordingToRectangles( new SimilarityChecker(), imageRotator, new RectangleFinder()), imageRotator, new DarkAreaExtractor()); var templatesFolderPath = $"{storageFolderPath}\\{Resources.Resources.TemplatesFolder}"; whiteBoardExtractor.DetectAndCrop(participantStorageFolderPath, templatesFolderPath); return Ok(); } catch (Exception e) { return BadRequest(e.ToString()); } } [HttpGet] [Route("ImageApi/Session/{sessionPin:long}/Image/{participantOrder}")] public HttpResponseMessage GetLastImage(long sessionPin, string participantOrder) { var session = _sessionService.GetSession(sessionPin); if (session == null || !session.IsActive) { return CreateBadRequestResponse(Resources.Resources.NoSessionWithTheGivenPin); } if (!session.BothParticipantsJoined) { return CreateBadRequestResponse(Resources.Resources.NotAllParticipantsJoinedSession); } var filePath = GetOutputFilePath(participantOrder); return CreateResponseMessageFromFile(filePath); } private static HttpResponseMessage CreateBadRequestResponse(string responseMessage) { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(responseMessage) }; return response; } private static HttpResponseMessage CreateResponseMessageFromFile(string filePath) { var fileContent = System.IO.File.ReadAllBytes(filePath); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(fileContent) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); return result; } [HttpGet] [Route("ImageApi/Session/{sessionPin:long}/Image/{participantOrder}/Dark")] public HttpResponseMessage GetLastImageWithOnlyDarkAreas(long sessionPin, string participantOrder) { if (!SessionIsValid(sessionPin)) { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(Resources.Resources.NoSessionWithTheGivenPin) }; return response; } var filePath = GetDarkOutputFilePath(participantOrder); return CreateResponseMessageFromFile(filePath); } private bool SessionIsValid(long sessionPin) { var session = _sessionService.GetSession(sessionPin); return session != null && session.IsActive && session.BothParticipantsJoined; } private static string GetOutputFilePath(string participantOrder) { var outputFolderParentFolder = participantOrder == "A" ? "B" : "A"; var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}\\{Resources.Resources.StorageFolder}\\{outputFolderParentFolder}\\{Resources.Resources.OutputFolder}\\image.jpg"; return filePath; } private static string GetDarkOutputFilePath(string participantOrder) { var outputFolderParentFolder = participantOrder == "A" ? "B" : "A"; var filePath1 = $"{AppDomain.CurrentDomain.BaseDirectory}\\{Resources.Resources.StorageFolder}\\{outputFolderParentFolder}\\{Resources.Resources.OutputFolder}\\dark.jpg"; var filePath = filePath1; return filePath; } } }
40.903614
182
0.647423
[ "BSD-2-Clause" ]
Zuehlke/SharedWhiteboard
WebApp/SharedWhiteBoard/Controllers/ImageController.cs
6,793
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.DotNet.DarcLib { public enum GitRepoType { GitHub, Vsts } }
24
71
0.698718
[ "MIT" ]
akoeplinger/arcade
src/Microsoft.DotNet.Darc/src/DarcLib/Models/Darc/GitRepoType.cs
312
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RemotingShared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RemotingShared")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8c6d2bfb-f209-4dcc-aa17-e5ea00cf1c96")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.72973
84
0.748567
[ "MIT" ]
AhmedKhalil777/DOTNET-Learning
Module 25 Remoting & Marshaling/RemoteSample/RemotingShared/Properties/AssemblyInfo.cs
1,399
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace Fap.Workflow.Engine.Enums { public enum FlowMessageEnum { [Description("通知审批人")] NoticeApprover, [Description("完成通知申请人")] CompleteNoticeApplier, } }
16.833333
35
0.676568
[ "Apache-2.0" ]
48355746/FapCore3.0
src/Fap.Workflow/Engine/Enums/FlowMessageEnum.cs
329
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Runtime.Serialization; using OpenSearch.Net.Utf8Json; namespace Osc { [DataContract] [JsonFormatter(typeof(ConcreteBulkIndexResponseItemFormatter<BulkCreateResponseItem>))] public class BulkCreateResponseItem : BulkResponseItemBase { public override string Operation { get; } = "create"; } }
34.65
88
0.77417
[ "Apache-2.0" ]
Bit-Quill/opensearch-net
src/Osc/Document/Multiple/Bulk/BulkResponseItem/BulkCreateResponseItem.cs
1,386
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests { public SymbolCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override CompletionProvider CreateCompletionProvider() { return new SymbolCompletionProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EmptyFile() { await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EmptyFile_Interactive() { await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EmptyFileWithUsing() { await VerifyItemIsAbsentAsync(@"using System; $$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(@"using System; $$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EmptyFileWithUsing_Interactive() { await VerifyItemExistsAsync(@"using System; $$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemExistsAsync(@"using System; $$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashR() { await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashLoad() { await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirective() { await VerifyItemIsAbsentAsync(@"using $$", @"String"); await VerifyItemIsAbsentAsync(@"using $$ = System", @"System"); await VerifyItemExistsAsync(@"using $$", @"System"); await VerifyItemExistsAsync(@"using T = $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegionWithUsing() { await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegionWithUsing() { await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineXmlComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenCharLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute1() { await VerifyItemExistsAsync(@"[assembly: $$]", @"System"); await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SystemAttributeIsNotAnAttribute() { var content = @"[$$] class CL {}"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeAttribute() { var content = @"[$$] class CL {}"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamAttribute() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodAttribute() { var content = @"class CL { [$$] void Method() {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodTypeParamAttribute() { var content = @"class CL{ void Method<[A$$]T> () {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamAttribute() { var content = @"class CL{ void Method ([$$]int i) {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_TopLevel() { var source = @"namespace $$ { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_Nested() { var source = @"; namespace System { namespace $$ { } }"; await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers() { var source = @"using System; namespace $$"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelWithPeer() { var source = @" namespace A { } namespace $$"; await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithNoPeers() { var source = @" namespace A { namespace $$ }"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithPeer() { var source = @" namespace A { namespace B { } namespace $$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() { var source = @"namespace N$$S"; await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNested() { var source = @" namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace $$ namespace C1 { } } namespace B.C2 { } } namespace A.B.C3 { }"; // Ideally, all the C* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // C1 => A.B.?.C1 // C2 => A.B.B.C2 // C3 => A.A.B.C3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); // Because of the above, B does end up in the completion list // since A.B.B appears to be a peer of the new declaration await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NoPeers() { var source = @"namespace A.$$"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer() { var source = @" namespace A.B { } namespace A.$$"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NestedWithPeer() { var source = @" namespace A { namespace B.C { } namespace B.$$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNested() { var source = @" namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem.Runtime { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnKeyword() { var source = @"name$$space System { }"; await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnNestedKeyword() { var source = @" namespace System { name$$space Runtime { } }"; await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace C.$$ namespace C.D1 { } } namespace B.C.D2 { } } namespace A.B.C.D3 { }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); // Ideally, all the D* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // D1 => A.B.C.C.?.D1 // D2 => A.B.B.C.D2 // D3 => A.A.B.C.D3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnderNamespace() { await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType1() { await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType2() { var content = @"namespace NS { class CL {} $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideProperty() { var content = @"class C { private string name; public string Name { set { name = $$"; await VerifyItemExistsAsync(content, @"value"); await VerifyItemExistsAsync(content, @"C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDot() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingAlias() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMember() { var content = @"class CL { $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMemberAccessibility() { var content = @"class CL { public $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BadStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameter() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameterList() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionTypePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StackAllocArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseTypeOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DeclarationStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VariableDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementNoToken() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldDeclaration() { var content = @"class CL { $$ i"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventFieldDeclaration() { var content = @"class CL { event $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclaration() { var content = @"class CL { explicit operator $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclarationNoToken() { var content = @"class CL { explicit $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PropertyDeclaration() { var content = @"class CL { $$ Prop {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventDeclaration() { var content = @"class CL { event $$ Event {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IndexerDeclaration() { var content = @"class CL { $$ this"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter() { var content = @"class CL { void Method($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayType() { var content = @"class CL { $$ ["; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PointerType() { var content = @"class CL { $$ *"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableType() { var content = @"class CL { $$ ?"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateDeclaration() { var content = @"class CL { delegate $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration() { var content = @"class CL { $$ M("; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OperatorDeclaration() { var content = @"class CL { $$ operator"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Argument() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseInPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LetClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OrderingExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SelectClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThrowStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System"); } [WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YieldReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LockStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EqualsValueClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementInitializersPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementConditionOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementIncrementorsPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhileStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayRankSpecifierSizesPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrefixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PostfixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenTruePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenFalsePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseInExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseLeftExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseRightExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhereClauseConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseGroupExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseByExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IfStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchLabelCase() { var content = @"switch(i) { case $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InitializerExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseList() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseAnotherWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause1() { await VerifyItemExistsAsync(@"class CL<T> where $$", @"T"); await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T"); await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause2() { await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause3() { await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1"); await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseListWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedName() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedNamespace() { await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedType() { await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstructorInitializer() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof2() { await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof2() { await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default2() { await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x"); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Checked() { await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x"); } [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Unchecked() { await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Locals() { await VerifyItemExistsAsync(@"class c { void M() { string foo; $$", "foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameters() { await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommonTypesInNewExpressionContext() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionForUnboundTypes() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { foo.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInTypeOf() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInDefault() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInSizeOf() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInGenericParameterList() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterNullLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterTrueLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterFalseLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterCharLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterStringLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterVerbatimStringLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterNumericLiteral() { // NOTE: the Completion command handler will suppress this case if the user types '.', // but we still need to show members if the user specifically invokes statement completion here. await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterParenthesizedNullLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedTrueLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedFalseLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedCharLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedStringLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedVerbatimStringLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedNumericLiteral() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterArithmeticExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals"); } [WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceTypesAvailableInUsingAlias() { await VerifyItemExistsAsync(@"using S = System.$$", "String"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember1() { var markup = @" class A { private void Hidden() { } protected void Foo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Foo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember2() { var markup = @" class A { private void Hidden() { } protected void Foo() { } } class B : A { void Bar() { this.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Foo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember3() { var markup = @" class A { private void Hidden() { } protected void Foo() { } } class B : A { void Bar() { base.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Foo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember1() { var markup = @" class A { private static void Hidden() { } protected static void Foo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Foo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember2() { var markup = @" class A { private static void Hidden() { } protected static void Foo() { } } class B : A { void Bar() { B.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Foo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember3() { var markup = @" class A { private static void Hidden() { } protected static void Foo() { } } class B : A { void Bar() { A.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Foo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedInstanceAndStaticMembers() { var markup = @" class A { private static void HiddenStatic() { } protected static void FooStatic() { } private void HiddenInstance() { } protected void FooInstance() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "HiddenStatic"); await VerifyItemExistsAsync(markup, "FooStatic"); await VerifyItemIsAbsentAsync(markup, "HiddenInstance"); await VerifyItemExistsAsync(markup, "FooInstance"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer1() { var markup = @" class C { void M() { for (int i = 0; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer2() { var markup = @" class C { void M() { for (int i = 0; i < 10; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersInClass() { var markup = @" class C<T, R> { $$ } "; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInLambda() { var markup = @" using System; class C { void M() { Func<int, int> f = (ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInLambda() { var markup = @" using System; class C { void M() { Func<int, int> f = (out $$ } } "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType1() { var markup = @" class Q { $$ class R { } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType2() { var markup = @" class Q { class R { $$ } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType3() { var markup = @" class Q { class R { } $$ } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Regular() { var markup = @" class Q { class R { } } $$"; // At EOF await VerifyItemIsAbsentAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Script() { var markup = @" class Q { class R { } } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType5() { var markup = @" class Q { class R { } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType6() { var markup = @" class Q { class R { $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenTypeAndLocal() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void foo() { int i = 5; i.$$ List<string> ml = new List<string>(); } }"; await VerifyItemExistsAsync(markup, "CompareTo"); } [WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterNewInScript() { var markup = @" using System; new $$"; await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodsInScript() { var markup = @" using System.Linq; var a = new int[] { 1, 2 }; a.$$"; await VerifyItemExistsAsync(markup, "ElementAt<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionsInForLoopInitializer() { var markup = @" public class C { public void M() { int count = 0; for ($$ "; await VerifyItemExistsAsync(markup, "count"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression1() { var markup = @" public class C { public void M() { System.Func<int, int> f = arg => { arg = 2; return arg; }.$$ } } "; await VerifyItemIsAbsentAsync(markup, "ToString"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression2() { var markup = @" public class C { public void M() { ((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$ } } "; await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemExistsAsync(markup, "Invoke"); } [WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InMultiLineCommentAtEndOfFile() { var markup = @" using System; /*$$"; await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersAtEndOfFile() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Outer<T> { class Inner<U> { static void F(T t, U u) { return; } public static void F(T t) { Outer<$$"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForCase() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "case 0:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "default:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchPresentForDefault() { var markup = @" class Program { static void Main() { int x; switch (x) { default: goto $$"; await VerifyItemExistsAsync(markup, "default:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto1() { var markup = @" class Program { static void Main() { Foo: int Foo; goto $$"; await VerifyItemExistsAsync(markup, "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto2() { var markup = @" class Program { static void Main() { Foo: int Foo; goto Foo $$"; await VerifyItemIsAbsentAsync(markup, "Foo"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeName() { var markup = @" using System; [$$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifier() { var markup = @" using System; [assembly:$$ "; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeList() { var markup = @" using System; [CLSCompliant, $$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameBeforeClass() { var markup = @" using System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifierBeforeClass() { var markup = @" using System; [assembly:$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeArgumentList() { var markup = @" using System; [CLSCompliant($$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInsideClass() { var markup = @" using System; class C { $$ }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName1() { var markup = @" using Alias = System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName2() { var markup = @" using Alias = Foo; namespace Foo { } [$$ class C { }"; await VerifyItemIsAbsentAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName3() { var markup = @" using Alias = Foo; namespace Foo { class A : System.Attribute { } } [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace() { var markup = @" namespace Test { class MyAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace2() { var markup = @" namespace Test { namespace Two { class MyAttribute : System.Attribute { } [Test.Two.$$ class Program { } } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task KeywordsUsedAsLocals() { var markup = @" class C { void M() { var error = 0; var method = 0; var @int = 0; Console.Write($$ } }"; // preprocessor keyword await VerifyItemExistsAsync(markup, "error"); await VerifyItemIsAbsentAsync(markup, "@error"); // contextual keyword await VerifyItemExistsAsync(markup, "method"); await VerifyItemIsAbsentAsync(markup, "@method"); // full keyword await VerifyItemExistsAsync(markup, "@int"); await VerifyItemIsAbsentAsync(markup, "int"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords1() { var markup = @" class C { void M() { var from = new[]{1,2,3}; var r = from x in $$ } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords2() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where $$ == @where.Length select @from; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords3() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where @from == @where.Length select $$; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAlias() { var markup = @" class MyAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() { var markup = @" class namespaceAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariableInQuerySelect() { var markup = @" using System.Linq; class P { void M() { var src = new string[] { ""Foo"", ""Bar"" }; var q = from x in src select x.$$"; await VerifyItemExistsAsync(markup, "Length"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchGotoCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case MAX_SIZE: break; case FOO: goto case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInEnumMember() { var markup = @" class C { public const int FOO = 0; enum E { A = $$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute1() { var markup = @" class C { public const int FOO = 0; [System.AttributeUsage($$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute2() { var markup = @" class C { public const int FOO = 0; [System.AttributeUsage(FOO, $$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute3() { var markup = @" class C { public const int FOO = 0; [System.AttributeUsage(validOn: $$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute4() { var markup = @" class C { public const int FOO = 0; [System.AttributeUsage(AllowMultiple = $$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInParameterDefaultValue() { var markup = @" class C { public const int FOO = 0; void M(int x = $$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstField() { var markup = @" class C { public const int FOO = 0; const int BAR = $$"; await VerifyItemExistsAsync(markup, "FOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstLocal() { var markup = @" class C { public const int FOO = 0; void M() { const int BAR = $$"; await VerifyItemExistsAsync(markup, "FOO"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1Overload() { var markup = @" class C { void M(int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2Overloads() { var markup = @" class C { void M(int i) { } void M(out int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1GenericOverload() { var markup = @" class C { void M<T>(T i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2GenericOverloads() { var markup = @" class C { void M<T>(int i) { } void M<T>(out int i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionNamedGenericType() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "C<>", expectedDescriptionOrNull: "class C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionParameter() { var markup = @" class C<T> { void M(T foo) { $$"; await VerifyItemExistsAsync(markup, "foo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionGenericTypeParameter() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionAnonymousType() { var markup = @" class C { void M() { var a = new { }; $$ "; var expectedDescription = $@"({FeaturesResources.local_variable}) 'a a {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}"; await VerifyItemExistsAsync(markup, "a", expectedDescription); } [WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterNewInAnonymousType() { var markup = @" class Program { string field = 0; static void Main() { var an = new { new $$ }; } } "; await VerifyItemExistsAsync(markup, "Program"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticMethod() { var markup = @" class C { int x = 0; static void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticFieldInitializer() { var markup = @" class C { int x = 0; static int y = $$ } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticMethod() { var markup = @" class C { static int x = 0; static void M() { $$ } } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticFieldInitializer() { var markup = @" class C { static int x = 0; static int y = $$ } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { int i; class inner { void M() { $$ } } } "; await VerifyItemIsAbsentAsync(markup, "i"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { static int i; class inner { void M() { $$ } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyEnumMembersInEnumMemberAccess() { var markup = @" class C { enum x {a,b,c} void M() { x.$$ } } "; await VerifyItemExistsAsync(markup, "a"); await VerifyItemExistsAsync(markup, "b"); await VerifyItemExistsAsync(markup, "c"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoEnumMembersInEnumLocalAccess() { var markup = @" class C { enum x {a,b,c} void M() { var y = x.a; y.$$ } } "; await VerifyItemIsAbsentAsync(markup, "a"); await VerifyItemIsAbsentAsync(markup, "b"); await VerifyItemIsAbsentAsync(markup, "c"); await VerifyItemExistsAsync(markup, "Equals"); } [WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaParameterDot() { var markup = @" using System; using System.Linq; class A { public event Func<String, String> E; } class Program { static void Main(string[] args) { new A().E += ss => ss.$$ } } "; await VerifyItemExistsAsync(markup, "Substring"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAtRoot_Interactive() { await VerifyItemIsAbsentAsync( @"$$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterClass_Interactive() { await VerifyItemIsAbsentAsync( @"class C { } $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalStatement_Interactive() { await VerifyItemIsAbsentAsync( @"System.Console.WriteLine(); $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalVariableDeclaration_Interactive() { await VerifyItemIsAbsentAsync( @"int i = 0; $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInUsingAlias() { await VerifyItemIsAbsentAsync( @"using Foo = $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInEmptyStatement() { await VerifyItemIsAbsentAsync(AddInsideMethod( @"$$"), "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideSetter() { await VerifyItemExistsAsync( @"class C { int Foo { set { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideAdder() { await VerifyItemExistsAsync( @"class C { event int Foo { add { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideRemover() { await VerifyItemExistsAsync( @"class C { event int Foo { remove { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterDot() { await VerifyItemIsAbsentAsync( @"class C { int Foo { set { this.$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterArrow() { await VerifyItemIsAbsentAsync( @"class C { int Foo { set { a->$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterColonColon() { await VerifyItemIsAbsentAsync( @"class C { int Foo { set { a::$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInGetter() { await VerifyItemIsAbsentAsync( @"class C { int Foo { get { $$", "value"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int foo = 0; C? $$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int foo = 0; A? $$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterNullableTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int foo = 0; C? f$$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int foo = 0; b? $$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkAndPartialIdentifierInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int foo = 0; b? f$$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int foo = 0; C* $$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int foo = 0; A* $$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int foo = 0; C* f$$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int foo = 0; i* $$", "foo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskAndPartialIdentifierInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int foo = 0; i* f$$", "foo"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterEventFieldDeclaredInSameType() { await VerifyItemExistsAsync( @"class C { public event System.EventHandler E; void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterFullEventDeclaredInSameType() { await VerifyItemIsAbsentAsync( @"class C { public event System.EventHandler E { add { } remove { } } void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterEventDeclaredInDifferentType() { await VerifyItemIsAbsentAsync( @"class C { void M() { System.Console.CancelKeyPress.$$", "Invoke"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotInObjectInitializerMemberContext() { await VerifyItemIsAbsentAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$", "x"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task AfterPointerMemberAccess() { await VerifyItemExistsAsync(@" struct MyStruct { public int MyField; } class Program { static unsafe void Main(string[] args) { MyStruct s = new MyStruct(); MyStruct* ptr = &s; ptr->$$ }}", "MyField"); } // After @ both X and XAttribute are legal. We think this is an edge case in the language and // are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed. [WorkItem(11931, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task VerbatimAttributes() { var code = @" using System; public class X : Attribute { } public class XAttribute : Attribute { } [@X$$] class Class3 { } "; await VerifyItemExistsAsync(code, "X"); await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(async () => await VerifyItemExistsAsync(code, "XAttribute")); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; $$ } } ", "Console"); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for ($$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclaration() { // "int foo = foo = 1" is a legal declaration await VerifyItemExistsAsync(@" class Program { void M() { int foo = $$ } }", "foo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclarator() { // "int bar = bar = 1" is legal in a declarator await VerifyItemExistsAsync(@" class Program { void M() { int foo = 0, int bar = $$, int baz = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclaration() { await VerifyItemIsAbsentAsync(@" class Program { void M() { $$ int foo = 0; } }", "foo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclarator() { await VerifyItemIsAbsentAsync(@" class Program { void M() { int foo = $$, bar = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAfterDeclarator() { await VerifyItemExistsAsync(@" class Program { void M() { int foo = 0, int bar = $$ } }", "foo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAsOutArgumentInInitializerExpression() { await VerifyItemExistsAsync(@" class Program { void M() { int foo = Bar(out $$ } int Bar(out int x) { x = 3; return 5; } }", "foo"); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Foo.$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Foo.$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { Foo.$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways() { var markup = @" class Program { void M() { Foo.$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { Foo.$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { Foo.$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Foo foo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableNever() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Foo foo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar(this Foo foo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Foo foo, int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Foo foo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar(int x) { } } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Foo foo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Foo foo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class FooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Foo foo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverriddenSymbolsFilteredFromCompletionList() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" public class B { public virtual void Foo(int original) { } } public class D : B { public override void Foo(int derived) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { C c = new C(); c.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Foo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Foo() { } } public class D : B { public void Foo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { $$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Foo(T t) { } public void Foo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } public void Foo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { public void Foo(T t) { } public void Foo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } public void Foo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateNever() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAlways() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")] [WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")] [WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateNever() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { public int Bar { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAlways() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateNever() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAlways() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Foo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads1() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo() { } public Foo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads2() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateNever() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAlways() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateNever() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAlways() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Foo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Foo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Foo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" public class Foo : Bar { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Bar { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAlways() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public enum Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAdvanced() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public enum Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Always() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Foo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Never() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Foo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 0, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))] public class Foo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Foo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Foo().$$ } }"; var referencedCode = @" public class Foo { [System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestColorColor1() { var markup = @" class A { static void Foo() { } void Bar() { } static void Main() { A A = new A(); A.$$ } }"; await VerifyItemExistsAsync(markup, "Foo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType1() { var markup = @" using System; class C { public static void Main() { $$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType2() { var markup = @" using System; class C { public static void Main() { C$$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "IndexProp", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } [WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDeclarationAmbiguity() { var markup = @" using System; class Program { void Main() { Environment.$$ var v; } }"; await VerifyItemExistsAsync(markup, "CommandLine"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCursorOnClassCloseBrace() { var markup = @" using System; class Outer { class Inner { } $$}"; await VerifyItemExistsAsync(markup, "Inner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync1() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync2() { var markup = @" using System.Threading.Tasks; class Program { public async T$$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterAsyncInMethodBody() { var markup = @" using System.Threading.Tasks; class Program { void foo() { var x = async $$ } }"; await VerifyItemIsAbsentAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable1() { var markup = @" class Program { void foo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "foo", "void Program.foo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable2() { var markup = @" class Program { async void foo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "foo", "void Program.foo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable1() { var markup = @" using System.Threading; using System.Threading.Tasks; class Program { async Task foo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.foo() {WorkspacesResources.Usage_colon} {SyntaxFacts.GetText(SyntaxKind.AwaitKeyword)} foo();"; await VerifyItemWithMscorlib45Async(markup, "foo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable2() { var markup = @" using System.Threading.Tasks; class Program { async Task<int> foo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.foo() {WorkspacesResources.Usage_colon} int x = {SyntaxFacts.GetText(SyntaxKind.AwaitKeyword)} foo();"; await VerifyItemWithMscorlib45Async(markup, "foo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void foo() { $$ } }"; await VerifyItemExistsAsync(markup, "foo", $"[{CSharpFeaturesResources.deprecated}] void Program.foo()"); } [WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersOnDottingIntoUnboundType() { var markup = @" class Program { RegistryKey foo; static void Main(string[] args) { foo.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeArgumentsInConstraintAfterBaselist() { var markup = @" public class Foo<T> : System.Object where $$ { }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDestructor() { var markup = @" class C { ~C() { $$ "; await VerifyItemIsAbsentAsync(markup, "Finalize"); } [WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodOnCovariantInterface() { var markup = @" class Schema<T> { } interface ISet<out T> { } static class SetMethods { public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { } } class Context { public ISet<T> Set<T>() { return null; } } class CustomSchema : Schema<int> { } class Program { static void Main(string[] args) { var set = new Context().Set<CustomSchema>(); set.$$ "; await VerifyItemExistsAsync(markup, "ForSchemaSet<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachInsideParentheses() { var markup = @" using System; class C { void M() { foreach($$) "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldInitializerInP2P() { var markup = @" class Class { int i = Consts.$$; }"; var referencedCode = @" public static class Consts { public const int C = 1; }"; await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false); } [WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowWithEqualsSign() { var markup = @" class c { public int value {set; get; }} class d { void foo() { c foo = new c { value$$= } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterThisDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { this.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { base.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInScriptContext() { await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoNestedTypeWhenDisplayingInstance() { var markup = @" class C { class D { } void M2() { new C().$$ } }"; await VerifyItemIsAbsentAsync(markup, "D"); } [WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchVariableInExceptionFilter() { var markup = @" class C { void M() { try { } catch (System.Exception myExn) when ($$"; await VerifyItemExistsAsync(markup, "myExn"); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterExternAlias() { var markup = @" class C { void foo() { global::$$ } }"; await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExternAliasSuggested() { var markup = @" extern alias Bar; class C { void foo() { $$ } }"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassDestructor() { var markup = @" class C { class N { ~$$ } }"; await VerifyItemExistsAsync(markup, "N"); await VerifyItemIsAbsentAsync(markup, "C"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TildeOutsideClass() { var markup = @" class C { class N { } } ~$$"; await VerifyNoItemsExistAsync(markup, SourceCodeKind.Regular); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StructDestructor() { var markup = @" struct C { ~$$ }"; await VerifyItemExistsAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { int x; void foo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if FOO int x; #endif void foo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if FOO int x; #endif void foo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if FOO int x; #endif #if BAR void foo() { $$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if FOO int x; #endif #if BAR class G { public void DoGStuff() {} } #endif void foo() { new G().$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}"; await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { int xyz; $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { #if PROJ1 int xyz; #endif $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { LABEL: int xyz; goto $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.label}) LABEL"; await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] { 1, 2, 3 } select $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.range_variable}) ? y"; await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription); } [WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void Shared() { var x = GetThing(); x.$$ } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE public int x; #endif #if TWO public int x {get; set;} #endif void foo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"(field) int C.x"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if TWO public int x; #endif #if ONE public int x {get; set;} #endif void foo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = "int C.x { get; set; }"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessWalkUp() { var markup = @" public class B { public A BA; public B BB; } class A { public A AA; public A AB; public int? x; public void foo() { A a = null; var q = a?.$$AB.BA.AB.BA; } }"; await VerifyItemExistsAsync(markup, "AA"); await VerifyItemExistsAsync(markup, "AB"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped() { var markup = @" public struct S { public int? i; } class A { public S? s; public void foo() { A a = null; var q = a?.s?.$$; } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped2() { var markup = @" public struct S { public int? i; } class A { public S? s; public void foo() { var q = s?.$$i?.ToString(); } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterConditionalIndexing() { var markup = @" public struct S { public int? i; } class A { public S[] s; public void foo() { A a = null; var q = a?.s?[$$; } }"; await VerifyItemExistsAsync(markup, "System"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.$$b?.c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnSelf() { var markup = @"using System; [My] class X { [My$$] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnOuterType() { var markup = @"using System; [My] class Y { } [$$] class X { [My] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType() { var markup = @"abstract class Test { private int _field; public sealed class InnerTest : Test { public void SomeTest() { $$ } } }"; await VerifyItemExistsAsync(markup, "_field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType2() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { $$ // M recommended and accessible } class NN { void Test2() { // M inaccessible and not recommended } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType3() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN { void Test2() { $$ // M inaccessible and not recommended } } } }"; await VerifyItemIsAbsentAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType4() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN : N { void Test2() { $$ // M accessible and recommended. } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType5() { var markup = @" class D { public void Q() { } } class C<T> : D { class N { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "Q"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType6() { var markup = @" class Base<T> { public int X; } class Derived : Base<int> { class Nested { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "X"); } [WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoTypeParametersDefinedInCrefs() { var markup = @"using System; /// <see cref=""Program{T$$}""/> class Program<T> { }"; await VerifyItemIsAbsentAsync(markup, "T"); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList1() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<$$ } } "; await VerifyItemExistsAsync(markup, "Class1<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList2() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<string,$$ } } "; await VerifyItemExistsAsync(markup, "Class1<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionInAliasedType() { var markup = @" using IAlias = IFoo; ///<summary>summary for interface IFoo</summary> interface IFoo { } class C { I$$ } "; await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IFoo\r\nsummary for interface IFoo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinNameOf() { var markup = @" class C { void foo() { var x = nameof($$) } } "; await VerifyAnyItemExistsAsync(markup); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y1"); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y2"); } [WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteDeclarationExpressionType() { var markup = @" using System; class C { void foo() { var x = Console.$$ var y = 3; } } "; await VerifyItemExistsAsync(markup, "WriteLine"); } [WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticAndInstanceInNameOf() { var markup = @" using System; class C { class D { public int x; public static int y; } void foo() { var z = nameof(C.D.$$ } } "; await VerifyItemExistsAsync(markup, "x"); await VerifyItemExistsAsync(markup, "y"); } [WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForLocals() { var markup = @"class C { void M() { var x = nameof(T.z.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes2() { var markup = @"class C { void M() { var x = nameof(U.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes3() { var markup = @"class C { void M() { var x = nameof(N.$$) } } namespace N { public class U { public int nope; } } "; await VerifyItemExistsAsync(markup, "U"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes4() { var markup = @" using z = System; class C { void M() { var x = nameof(z.$$) } } "; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings1() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$ "; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings2() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$}""; } }"; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings3() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings4() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings5() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings6() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBeforeFirstStringHole() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBetweenStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task CompletionAfterTypeOfGetType() { await VerifyItemExistsAsync(AddInsideMethod( "typeof(int).GetType().$$"), "GUID"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives1() { var markup = @" using $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives2() { var markup = @" using N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives3() { var markup = @" using G = $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives4() { var markup = @" using G = N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives5() { var markup = @" using static $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives6() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates1() { var markup = @" using static $$ class A { } delegate void B(); namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates2() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } delegate void D(); namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces1() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } interface I { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces2() { var markup = @" using static $$ class A { } interface I { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods1() { var markup = @" using static A; using static B; static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Foo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods2() { var markup = @" using N; namespace N { static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Foo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods3() { var markup = @" using N; namespace N { static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Foo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods4() { var markup = @" using static N.A; using static N.B; namespace N { static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Foo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods5() { var markup = @" using static N.A; namespace N { static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Foo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods6() { var markup = @" using static N.B; namespace N { static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Foo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods7() { var markup = @" using N; using static N.B; namespace N { static class A { public static void Foo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$; } } "; await VerifyItemExistsAsync(markup, "Foo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinSameClassOfferedForCompletion() { var markup = @" public static class Test { static void TestB() { $$ } static void TestA(this string s) { } } "; await VerifyItemExistsAsync(markup, "TestA"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinParentClassOfferedForCompletion() { var markup = @" public static class Parent { static void TestA(this string s) { } static void TestC(string s) { } public static class Test { static void TestB() { $$ } } } "; await VerifyItemExistsAsync(markup, "TestA"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1() { var markup = @" using System; class C { void M(bool x) { try { } catch when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionContextCompletionWithinCast() { var markup = @" class Program { void M() { for (int i = 0; i < 5; i++) { var x = ($$) var y = 1; } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInPropertyInitializer() { var markup = @" class A { int abc; int B { get; } = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInPropertyInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInFieldLikeEventInitializer() { var markup = @" class A { Action abc; event Action B = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInFieldLikeEventInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldInitializer() { var markup = @" int aaa = 1; int bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldLikeEventInitializer() { var markup = @" Action aaa = null; event Action bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes1() { var markup = @" using A = System class C { A?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes2() { var markup = @" class C { System?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes3() { var markup = @" class C { System.Console?.$$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInIncompletePropertyDeclaration() { var markup = @" class Class1 { public string Property1 { get; set; } } class Class2 { public string Property { get { return this.Source.$$ public Class1 Source { get; set; } }"; await VerifyItemExistsAsync(markup, "Property1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionInShebangComments() { await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script); await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompoundNameTargetTypePreselection() { var markup = @" class Class1 { void foo() { int x = 3; string y = x.$$ } }"; await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer1() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer2() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { 1, $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer1() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void foo() { int i; var c = new C() { X = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer2() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void foo() { int i; var c = new C() { X = 1, Y = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } } }
30.400429
408
0.605406
[ "Apache-2.0" ]
Unknown6656/roslyn
src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs
269,295
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Iot.Device.Ssd1306.Command { public class SetInverseDisplay : ICommand { /// <summary> /// This command sets the display to be inverse. Displays a RAM data of 0 indicates an ON pixel. /// </summary> public SetInverseDisplay() { } /// <summary> /// The value that represents the command. /// </summary> public byte Id => 0xA7; /// <summary> /// Gets the bytes that represent the command. /// </summary> /// <returns>The bytes that represent the command.</returns> public byte[] GetBytes() { return new byte[] { Id }; } } }
29.032258
105
0.581111
[ "MIT" ]
491134648/iot
src/devices/Ssd1306/Command/SetInverseDisplay.cs
902
C#
using Castle.DynamicProxy; using FORCEBuild.Core; namespace FORCEBuild.Crosscutting { public class PropertyChangedNotifyPreparation:IFactoryProxyPreparation { public void GeneratePreparation(PreProxyEventArgs args) { var notifyBase = new NotifyBase(); args.Interceptors.Add(new PropertyNotifyInterceptor(notifyBase)); args.GenerationOptions.AddMixinInstance(notifyBase); } } }
30
77
0.711111
[ "Apache-2.0" ]
migeyusu/FORCEBuilds
FORCEBuilds/ForceBuild/Crosscutting/PropertyChangedNotifyPreparation.cs
452
C#
using System; using System.Drawing; namespace GuiLabs.Canvas.DrawStyle { public interface IDrawInfoFactory { ILineStyleInfo ProduceNewLineStyleInfo( Color theColor, int theWidth); IFillStyleInfo ProduceNewFillStyleInfo( Color theColor); IFontStyleInfo ProduceNewFontStyleInfo( string FamilyName, float size, System.Drawing.FontStyle theStyle); IPicture ProduceNewPicture( System.Drawing.Image image); IPicture ProduceNewTransparentPicture( System.Drawing.Image image, System.Drawing.Color transparentColor); } }
24.956522
43
0.75784
[ "MIT" ]
KirillOsenkov/LiveGeometry
Reference/VB.NET/Canvas/DrawStyle/Factory/IDrawInfoFactory.cs
574
C#
using System; using System.Threading.Tasks; using MailKit.Net.Smtp; using MimeKit; using SmartValley.Domain.Exceptions; namespace SmartValley.Application.Email { public class MailSender { private readonly SmtpOptions _smtpOptions; public MailSender(SmtpOptions smtpOptions) { _smtpOptions = smtpOptions; } public async Task SendAsync(string to, string subject, string body) { var message = CreateMessage(to, subject, body); using (var client = new SmtpClient()) { try { client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(_smtpOptions.Host, _smtpOptions.Port, _smtpOptions.UseSsl); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(_smtpOptions.UserName, _smtpOptions.Password); await client.SendAsync(message); await client.DisconnectAsync(true); } catch (Exception exception) { throw new EmailSendingFailedException(exception.ToString()); } } } private MimeMessage CreateMessage(string to, string subject, string body) { var message = new MimeMessage(); message.From.Add(new MailboxAddress(_smtpOptions.UserName)); message.To.Add(new MailboxAddress(to)); message.Subject = subject; var bodyBuilder = new BodyBuilder {HtmlBody = body}; message.Body = bodyBuilder.ToMessageBody(); return message; } } }
33.113208
105
0.580057
[ "MIT" ]
SmartValleyEcosystem/smartvalley
SmartValley.Application/Email/MailSender.cs
1,757
C#
namespace Amazon.Ec2 { public class RunInstancesMonitoringEnabled { public RunInstancesMonitoringEnabled() { } public RunInstancesMonitoringEnabled(bool enabled) { Enabled = enabled; } public bool Enabled { get; set; } } }
20.266667
59
0.578947
[ "MIT" ]
alexandercamps/Amazon
src/Amazon.Ec2/Actions/RunInstancesMonitoringEnabled.cs
306
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class CompilationErrorTests : CompilingTestBase { #region Symbol Error Tests private static readonly ModuleMetadata s_mod1 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod01); private static readonly ModuleMetadata s_mod2 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod02); [Fact()] public void CS0148ERR_BadDelegateConstructor() { var il = @" .class public auto ansi sealed F extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor( //object 'object', native int 'method') runtime managed { } // end of method F::.ctor .method public hidebysig newslot virtual instance void Invoke() runtime managed { } // end of method F::Invoke .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } // end of method F::BeginInvoke .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed { } // end of method F::EndInvoke } // end of class F "; var source = @" class C { void Goo() { F del = Goo; del(); //need to use del or the delegate receiver alone is emitted in optimized code. } } "; var comp = CreateCompilationWithILAndMscorlib40(source, il); var emitResult = comp.Emit(new System.IO.MemoryStream()); emitResult.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_BadDelegateConstructor, "Goo").WithArguments("F")); } /// <summary> /// This error is specific to netmodule scenarios /// We used to give error CS0011: The base class or interface 'A' in assembly 'xxx' referenced by type 'B' could not be resolved /// In Roslyn we do not know the context in which the lookup was occurring, so we give a new, more generic message. /// </summary> [WorkItem(546451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546451")] [Fact()] public void CS0011ERR_CantImportBase01() { var text1 = @"class A {}"; var text2 = @"class B : A {}"; var text = @" class Test { B b; void M() { Test x = b; } }"; var name1 = GetUniqueName(); var module1 = CreateCompilation(text1, options: TestOptions.ReleaseModule, assemblyName: name1); var module2 = CreateCompilation(text2, options: TestOptions.ReleaseModule, references: new[] { ModuleMetadata.CreateFromImage(module1.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); // use ref2 only var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_UnreferencedField), ReportDiagnostic.Suppress } }), references: new[] { ModuleMetadata.CreateFromImage(module2.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); comp.VerifyDiagnostics( // error CS8014: Reference to '1b2d660e-e892-4338-a4e7-f78ce7960ce9.netmodule' netmodule missing. Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments(name1 + ".netmodule"), // (8,18): error CS7079: The type 'A' is defined in a module that has not been added. You must add the module '2bddf16b-09e6-4c4d-bd08-f348e194eca4.netmodule'. // Test x = b; Diagnostic(ErrorCode.ERR_NoTypeDefFromModule, "b").WithArguments("A", name1 + ".netmodule"), // (8,18): error CS0029: Cannot implicitly convert type 'B' to 'Test' // Test x = b; Diagnostic(ErrorCode.ERR_NoImplicitConv, "b").WithArguments("B", "Test"), // (4,7): warning CS0649: Field 'Test.b' is never assigned to, and will always have its default value null // B b; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "b").WithArguments("Test.b", "null") ); } [Fact] public void CS0012ERR_NoTypeDef01() { var text = @"namespace NS { class Test { TC5<string, string> var; // inherit C1 from MDTestLib1.dll void M() { Test x = var; } } }"; var ref2 = TestReferences.SymbolsTests.MDTestLib2; var comp = CreateCompilation(text, references: new MetadataReference[] { ref2 }, assemblyName: "Test3"); comp.VerifyDiagnostics( // (9,22): error CS0012: The type 'C1<>.C2<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Test x = var; Diagnostic(ErrorCode.ERR_NoTypeDef, "var").WithArguments("C1<>.C2<>", "MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,22): error CS0029: Cannot implicitly convert type 'TC5<string, string>' to 'NS.Test' // Test x = var; Diagnostic(ErrorCode.ERR_NoImplicitConv, "var").WithArguments("TC5<string, string>", "NS.Test"), // (5,28): warning CS0649: Field 'NS.Test.var' is never assigned to, and will always have its default value null // TC5<string, string> var; // inherit C1 from MDTestLib1.dll Diagnostic(ErrorCode.WRN_UnassignedInternalField, "var").WithArguments("NS.Test.var", "null") ); } [Fact, WorkItem(8574, "DevDiv_Projects/Roslyn")] public void CS0029ERR_CannotImplicitlyConvertTypedReferenceToObject() { var text = @" class Program { static void M(System.TypedReference r) { var t = r.GetType(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // var t = r.GetType(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "r").WithArguments("System.TypedReference", "object")); } // CS0036: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0050ERR_BadVisReturnType() { var text = @"class MyClass { } public class MyClass2 { public static MyClass MyMethod() // CS0050 { return new MyClass(); } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisReturnType, Line = 7, Column = 27 }); } [Fact] public void CS0051ERR_BadVisParamType01() { var text = @"public class A { class B { } public static void F(B b) // CS0051 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType02() { var text = @"class A { protected class P1 { } public class N { public void f(P1 p) { } protected void g(P1 p) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 8, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType03() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 { public void M(B<A> arg) { } } public class C2 { public void M(B<object>.C<A> arg) { } } public class C3 { public void M(B<A>.C<object> arg) { } } public class C4 { public void M(B<B<A>>.C<object> arg) { } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>' is less accessible than method 'C1.M(B<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C1.M(B<A>)", "B<A>").WithLocation(8, 17), // (12,17): error CS0051: Inconsistent accessibility: parameter type 'B<object>.C<A>' is less accessible than method 'C2.M(B<object>.C<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C2.M(B<object>.C<A>)", "B<object>.C<A>").WithLocation(12, 17), // (16,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>.C<object>' is less accessible than method 'C3.M(B<A>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C3.M(B<A>.C<object>)", "B<A>.C<object>").WithLocation(16, 17), // (20,17): error CS0051: Inconsistent accessibility: parameter type 'B<B<A>>.C<object>' is less accessible than method 'C4.M(B<B<A>>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C4.M(B<B<A>>.C<object>)", "B<B<A>>.C<object>").WithLocation(20, 17)); } [Fact] public void CS0052ERR_BadVisFieldType() { var text = @"public class MyClass2 { public MyClass M; // CS0052 private class MyClass { } } public class MainClass { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisFieldType, Line = 3, Column = 20 }); } [Fact] public void CS0053ERR_BadVisPropertyType() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class B { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class D { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.Q", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("A.R", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.S", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("A.V", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.W", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.B.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.B.Q", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.B.S", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.B.W", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("C.R", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.S", "C.PrivateClass").WithLocation(34, 25), // (370): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("C.V", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.W", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.D.S", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.D.W", "C.PrivateClass").WithLocation(48, 31)); } [ClrOnlyFact] public void CS0054ERR_BadVisIndexerReturn() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class B { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class D { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[object]", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string]", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double]", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string, string]", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double, double]", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.B.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[object]", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double]", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double, double]", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string]", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double]", "C.PrivateClass").WithLocation(34, 25), // (370): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string, string]", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double, double]", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double]", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double, double]", "C.PrivateClass").WithLocation(48, 31)); } [Fact] public void CS0055ERR_BadVisIndexerParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public int this[MyClass myClass] // CS0055 { get { return 0; } } } public class MyClass3 { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisIndexerParam, Line = 7, Column = 16 }); } [Fact] public void CS0056ERR_BadVisOpReturn() { var text = @"class MyClass { } public class A { public static implicit operator MyClass(A a) // CS0056 { return new MyClass(); } public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,28): error CS0056: Inconsistent accessibility: return type 'MyClass' is less accessible than operator 'A.implicit operator MyClass(A)' // public static implicit operator MyClass(A a) // CS0056 Diagnostic(ErrorCode.ERR_BadVisOpReturn, "MyClass").WithArguments("A.implicit operator MyClass(A)", "MyClass") ); } [Fact] public void CS0057ERR_BadVisOpParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public static implicit operator MyClass2(MyClass iii) // CS0057 { return new MyClass2(); } public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (77): error CS0057: Inconsistent accessibility: parameter type 'MyClass' is less accessible than operator 'MyClass2.implicit operator MyClass2(MyClass)' // public static implicit operator MyClass2(MyClass iii) // CS0057 Diagnostic(ErrorCode.ERR_BadVisOpParam, "MyClass2").WithArguments("MyClass2.implicit operator MyClass2(MyClass)", "MyClass")); } [Fact] public void CS0058ERR_BadVisDelegateReturn() { var text = @"class MyClass { } public delegate MyClass MyClassDel(); // CS0058 public class A { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisDelegateReturn, Line = 5, Column = 25 }); } [WorkItem(542005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542005")] [Fact] public void CS0058ERR_BadVisDelegateReturn02() { var text = @" public class Outer { protected class Test { } public delegate Test MyDelegate(); }"; CreateCompilation(text).VerifyDiagnostics( // (5,26): error CS0058: Inconsistent accessibility: return type 'Outer.Test' is less accessible than delegate 'Outer.MyDelegate' // public delegate Test MyDelegate(); Diagnostic(ErrorCode.ERR_BadVisDelegateReturn, "MyDelegate").WithArguments("Outer.MyDelegate", "Outer.Test").WithLocation(5, 26) ); } [Fact] public void CS0059ERR_BadVisDelegateParam() { var text = @" class MyClass {} //defaults to internal accessibility public delegate void MyClassDel(MyClass myClass); // CS0059 "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,22): error CS0059: Inconsistent accessibility: parameter type 'MyClass' is less accessible than delegate 'MyClassDel' // public delegate void MyClassDel(MyClass myClass); // CS0059 Diagnostic(ErrorCode.ERR_BadVisDelegateParam, "MyClassDel").WithArguments("MyClassDel", "MyClass") ); } [Fact] public void CS0060ERR_BadVisBaseClass() { var text = @" namespace NS { internal class MyBase { } public class MyClass : MyBase { } public class Outer { private class MyBase { } protected class MyClass : MyBase { } protected class MyBase01 { } protected internal class MyClass01 : MyBase { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 34 }); } [WorkItem(539511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539511")] [Fact] public void CS0060ERR_BadVisBaseClass02() { var text = @" public class A<T> { public class B<S> : A<B<D>.C> { public class C { } } protected class D { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 18 }); } [WorkItem(539512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539512")] [Fact] public void CS0060ERR_BadVisBaseClass03() { var text = @" public class A { protected class B { protected class C { } } } internal class F : A { private class D : B { public class E : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 22 }); } [WorkItem(539546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539546")] [Fact] public void CS0060ERR_BadVisBaseClass04() { var text = @" public class A<T> { private class B : A<B.C> { private class C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 19 }); } [WorkItem(539562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539562")] [Fact] public void CS0060ERR_BadVisBaseClass05() { var text = @" class A<T> { class B : A<B> { public class C : B { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(539950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539950")] [Fact] public void CS0060ERR_BadVisBaseClass06() { var text = @" class A : C<E.F> { public class B { public class D { protected class F { } } } } class C<T> { } class E : A.B.D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // E.F is inaccessible where written; cascaded ERR_BadVisBaseClass is therefore suppressed new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 2, Column = 15 }); } [Fact] public void CS0060ERR_BadVisBaseClass07() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 : B<A> { } public class C2 : B<object>.C<A> { } public class C3 : B<A>.C<object> { } public class C4 : B<B<A>>.C<object> { }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0060: Inconsistent accessibility: base class 'B<A>' is less accessible than class 'C1' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "B<A>").WithLocation(6, 14), // (7,14): error CS0060: Inconsistent accessibility: base class 'B<object>.C<A>' is less accessible than class 'C2' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C2").WithArguments("C2", "B<object>.C<A>").WithLocation(7, 14), // (8,14): error CS0060: Inconsistent accessibility: base class 'B<A>.C<object>' is less accessible than class 'C3' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C3").WithArguments("C3", "B<A>.C<object>").WithLocation(8, 14), // (9,14): error CS0060: Inconsistent accessibility: base class 'B<B<A>>.C<object>' is less accessible than class 'C4' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C4").WithArguments("C4", "B<B<A>>.C<object>").WithLocation(9, 14)); } [Fact] public void CS0060ERR_BadVisBaseClass08() { var source = @"public class A { internal class B { public interface C { } } } public class B<T> : A { } public class C : B<A.B.C> { }"; CreateCompilation(source).VerifyDiagnostics( // (9,14): error CS0060: Inconsistent accessibility: base class 'B<A.B.C>' is less accessible than class 'C' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("C", "B<A.B.C>").WithLocation(9, 14)); } [Fact] public void CS0061ERR_BadVisBaseInterface() { var text = @"internal interface A { } public interface AA : A { } // CS0061 // OK public interface B { } internal interface BB : B { } internal interface C { } internal interface CC : C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseInterface, Line = 2, Column = 18 }); } [Fact] public void CS0065ERR_EventNeedsBothAccessors() { var text = @"using System; public delegate void Eventhandler(object sender, int e); public class MyClass { public event EventHandler E1 { } // CS0065, public event EventHandler E2 { add { } } // CS0065, public event EventHandler E3 { remove { } } // CS0065, } "; CreateCompilation(text).VerifyDiagnostics( // (5,31): error CS0065: 'MyClass.E1': event property must have both add and remove accessors // public event EventHandler E1 { } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("MyClass.E1"), // (6,31): error CS0065: 'MyClass.E2': event property must have both add and remove accessors // public event EventHandler E2 { add { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("MyClass.E2"), // (71): error CS0065: 'MyClass.E3': event property must have both add and remove accessors // public event EventHandler E3 { remove { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E3").WithArguments("MyClass.E3")); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface01() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent")); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface02() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 35), // (6,43): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 43)); CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 35), // (6,43): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 43), // (6,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 32), // (6,37): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 37) ); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface03() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} remove {} } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (5,39): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 39) ); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface04() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors // event myDelegate myevent { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent").WithLocation(5, 22) ); } [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface05() { var text = @" public interface I2 { } public interface I1 { event System.Action I2.P10; } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P10").WithLocation(6, 28), // (6,25): error CS0540: 'I1.P10': containing type does not implement interface 'I2' // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P10", "I2").WithLocation(6, 25), // (6,28): error CS0539: 'I1.P10' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P10").WithArguments("I1.P10").WithLocation(6, 28) ); } [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface06() { var text = @" public interface I2 { } public interface I1 { event System.Action I2. P10; } "; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS0540: 'I1.P10': containing type does not implement interface 'I2' // event System.Action I2. Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P10", "I2").WithLocation(6, 25), // (7,1): error CS0071: An explicit interface implementation of an event must use event accessor syntax // P10; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P10").WithLocation(7, 1), // (7,1): error CS0539: 'I1.P10' in explicit interface declaration is not found among members of the interface that can be implemented // P10; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P10").WithArguments("I1.P10").WithLocation(7, 1) ); } [Fact] public void CS0066ERR_EventNotDelegate() { var text = @" public class C { public event C Click; // CS0066 } "; CreateCompilation(text).VerifyDiagnostics( // (4,20): error CS0066: 'C.Click': event must be of a delegate type // public event C Click; // CS0066 Diagnostic(ErrorCode.ERR_EventNotDelegate, "Click").WithArguments("C.Click"), // (4,20): warning CS0067: The event 'C.Click' is never used // public event C Click; // CS0066 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("C.Click")); } [Fact] public void CS0068ERR_InterfaceEventInitializer() { var text = @" delegate void MyDelegate(); interface I { event MyDelegate d = new MyDelegate(M.f); // CS0068 } class M { event MyDelegate d = new MyDelegate(M.f); public static void f() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0068: 'I.d': event in interface cannot have initializer // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "d").WithArguments("I.d").WithLocation(6, 22), // (6,22): warning CS0067: The event 'I.d' is never used // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "d").WithArguments("I.d").WithLocation(6, 22)); } [Fact] public void CS0072ERR_CantOverrideNonEvent() { var text = @"delegate void MyDelegate(); class Test1 { public virtual event MyDelegate MyEvent; public virtual void VMeth() { } } class Test2 : Test1 { public override event MyDelegate VMeth // CS0072 { add { VMeth += value; } remove { VMeth -= value; } } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,38): error CS0072: 'Test2.VMeth': cannot override; 'Test1.VMeth()' is not an event // public override event MyDelegate VMeth // CS0072 Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "VMeth").WithArguments("Test2.VMeth", "Test1.VMeth()"), // (5,37): warning CS0067: The event 'Test1.MyEvent' is never used // public virtual event MyDelegate MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test1.MyEvent")); } [Fact] public void CS0074ERR_AbstractEventInitializer() { var text = @" delegate void D(); abstract class Test { public abstract event D e = null; // CS0074 } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0074: 'Test.e': abstract event cannot have initializer // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.ERR_AbstractEventInitializer, "e").WithArguments("Test.e").WithLocation(6, 29), // (6,29): warning CS0414: The field 'Test.e' is assigned but its value is never used // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("Test.e").WithLocation(6, 29)); } [Fact] public void CS0076ERR_ReservedEnumerator() { var text = @"enum E { value__ } enum F { A, B, value__ } enum G { X = 0, value__ = 1, Z = value__ + 1 } enum H { Value__ } // no error class C { E value__; // no error static void M() { F value__; // no error } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (1,10): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum E { value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (2,16): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum F { A, B, value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (3,17): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum G { X = 0, value__ = 1, Z = value__ + 1 } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (10,11): warning CS0168: The variable 'value__' is declared but never used // F value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedVar, "value__").WithArguments("value__"), // (7,7): warning CS0169: The field 'C.value__' is never used // E value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "value__").WithArguments("C.value__") ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. // TODO: vsadov, the error recovery would be much nicer here if we consumed "int", bu tneed to consider other cases. CreateCompilationWithMscorlib46(text, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int").WithLocation(5, 11), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(5, 14), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">").WithLocation(5, 14), // (5,15): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "(").WithLocation(5, 15), // (5,16): error CS8124: Tuple must contain at least two elements. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 16), // (5,18): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 18), // (5,18): error CS1026: ) expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(5, 18), // (5,15): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 15), // (5,9): error CS0161: 'C.F<>(int, (?, ?))': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int, (?, ?))").WithLocation(5, 9) ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01WithCSharp6() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. CreateCompilationWithMscorlib46(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int").WithLocation(5, 11), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(5, 14), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">").WithLocation(5, 14), // (5,15): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "(").WithLocation(5, 15), // (5,15): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "()").WithArguments("tuples", "7.0").WithLocation(5, 15), // (5,16): error CS8124: Tuple must contain at least two elements. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 16), // (5,18): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 18), // (5,18): error CS1026: ) expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(5, 18), // (5,15): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 15), // (5,9): error CS0161: 'C.F<>(int, (?, ?))': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int, (?, ?))").WithLocation(5, 9) ); } [Fact] public void CS0082ERR_MemberReserved01() { CreateCompilation( @"class C { public void set_P(int i) { } public int P { get; set; } public int get_P() { return 0; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(4, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(4, 25)); } [Fact] public void CS0082ERR_MemberReserved02() { CreateCompilation( @"class A { public void set_P(int i) { } } partial class B : A { public int P { get { return 0; } set { } } } partial class B { partial void get_P(); public void set_P() { } } partial class B { partial void get_P() { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "B").WithLocation(9, 9)); } [Fact] public void CS0082ERR_MemberReserved03() { CreateCompilation( @"abstract class C { public abstract object P { get; } protected abstract object Q { set; } internal object R { get; set; } protected internal object S { get { return null; } } private object T { set { } } object U { get { return null; } set { } } object get_P() { return null; } void set_P(object value) { } private object get_Q() { return null; } private void set_Q(object value) { } protected internal object get_R() { return null; } protected internal void set_R(object value) { } internal object get_S() { return null; } internal void set_S(object value) { } protected object get_T() { return null; } protected void set_T(object value) { } public object get_U() { return null; } public void set_U(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(3, 32), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C").WithLocation(3, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "Q").WithArguments("get_Q", "C").WithLocation(4, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_R", "C").WithLocation(5, 25), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(5, 30), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_S", "C").WithLocation(6, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "S").WithArguments("set_S", "C").WithLocation(6, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "T").WithArguments("get_T", "C").WithLocation(7, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_T", "C").WithLocation(7, 24), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_U", "C").WithLocation(8, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_U", "C").WithLocation(8, 37)); } [Fact] public void CS0082ERR_MemberReserved04() { CreateCompilationWithMscorlib40AndSystemCore( @"class A<T, U> { public T P { get; set; } // CS0082 public U Q { get; set; } // no error public U R { get; set; } // no error public void set_P(T t) { } public void set_Q(object o) { } public void set_R(T t) { } } class B : A<object, object> { } class C { public dynamic P { get; set; } // CS0082 public dynamic Q { get; set; } // CS0082 public object R { get; set; } // CS0082 public object S { get; set; } // CS0082 public void set_P(object o) { } public void set_Q(dynamic o) { } public void set_R(object o) { } public void set_S(dynamic o) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "A<T, U>").WithLocation(3, 23), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(15, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(16, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(17, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(18, 28)); } [Fact] public void CS0082ERR_MemberReserved05() { CreateCompilation( @"class C { object P { get; set; } object Q { get; set; } object R { get; set; } object[] S { get; set; } public object get_P(object o) { return null; } // CS0082 public void set_P() { } public void set_P(ref object o) { } public void get_Q() { } // CS0082 public object set_Q(object o) { return null; } // CS0082 public object set_Q(out object o) { o = null; return null; } void set_S(params object[] args) { } // CS0082 } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_Q", "C").WithLocation(4, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 21), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(6, 23)); } [Fact] public void CS0082ERR_MemberReserved06() { // No errors for explicit interface implementation. CreateCompilation( @"interface I { int get_P(); void set_P(int o); } class C : I { public int P { get; set; } int I.get_P() { return 0; } void I.set_P(int o) { } } ") .VerifyDiagnostics(); } [WorkItem(539770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539770")] [Fact] public void CS0082ERR_MemberReserved07() { // No errors for explicit interface implementation. CreateCompilation( @"class C { public object P { get { return null; } } object get_P() { return null; } void set_P(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C"), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C")); } [Fact] public void CS0082ERR_MemberReserved08() { CreateCompilation( @"class C { public event System.Action E; void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,32): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("add_E", "C"), // (3,32): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("remove_E", "C"), // (3,32): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0082ERR_MemberReserved09() { CreateCompilation( @"class C { public event System.Action E { add { } remove { } } void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,36): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "add").WithArguments("add_E", "C"), // (3,44): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "remove").WithArguments("remove_E", "C")); } [Fact] public void CS0100ERR_DuplicateParamName01() { var text = @"namespace NS { interface IGoo { void M1(byte b, sbyte b); } struct S { public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (5,31): error CS0100: The parameter name 'b' is a duplicate // void M1(byte b, sbyte b); Diagnostic(ErrorCode.ERR_DuplicateParamName, "b").WithArguments("b").WithLocation(5, 31), // (10,45): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 45), // (10,59): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 59), // (10,77): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 77), // (10,82): error CS0229: Ambiguity between 'object' and 'ref string' // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_AmbigMember, "p").WithArguments("object", "ref string").WithLocation(10, 82) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS01() { var text = @"namespace NS { struct Test { } class Test { } interface Test { } namespace NS1 { interface A<T, V> { } class A<T, V> { } class A<T, V> { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 10, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 11, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS02() { var text = @"namespace NS { interface IGoo<T, V> { } class IGoo<T, V> { } struct SS { } public class SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS03() { var text = @"namespace NS { interface IGoo<T, V> { } interface IGoo<T, V> { } struct SS { } public struct SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS04() { var text = @"namespace NS { partial class Goo<T, V> { } // no error, because ""partial"" partial class Goo<T, V> { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0102ERR_DuplicateNameInClass01() { var text = @"class A { int n = 0; long n = 1; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,10): error CS0102: The type 'A' already contains a definition for 'n' // long n = 1; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "n").WithArguments("A", "n"), // (3,9): warning CS0414: The field 'A.n' is assigned but its value is never used // int n = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n"), // (4,10): warning CS0414: The field 'A.n' is assigned but its value is never used // long n = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n") ); var classA = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; var ns = classA.GetMembers("n"); Assert.Equal(2, ns.Length); foreach (var n in ns) { Assert.Equal(TypeKind.Struct, (n as FieldSymbol).Type.TypeKind); } } [Fact] public void CS0102ERR_DuplicateNameInClass02() { CreateCompilation( @"namespace NS { class C { interface I<T, U> { } interface I<T, U> { } struct S { } public struct S { } } struct S<X> { X x; C x; } } ") .VerifyDiagnostics( // (6,19): error CS0102: The type 'NS.C' already contains a definition for 'I' // interface I<T, U> { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I"), // (9,23): error CS0102: The type 'NS.C' already contains a definition for 'S' // public struct S { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S"), // (14,11): error CS0102: The type 'NS.S<X>' already contains a definition for 'x' // C x; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("NS.S<X>", "x"), // (13,11): warning CS0169: The field 'NS.S<X>.x' is never used // X x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x"), // (14,11): warning CS0169: The field 'NS.S<X>.x' is never used // C x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x") ); // Dev10 miss this with previous errors } [Fact] public void CS0102ERR_DuplicateNameInClass03() { CreateCompilation( @"namespace NS { class C { interface I<T> { } class I<U> { } struct S { } class S { } enum E { } interface E { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I").WithLocation(6, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S").WithLocation(8, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("NS.C", "E").WithLocation(10, 19)); } [Fact] public void CS0104ERR_AmbigContext01() { var text = @"namespace n1 { public interface IGoo<T> { } class A { } } namespace n3 { using n1; using n2; namespace n2 { public interface IGoo<V> { } public class A { } } public class C<X> : IGoo<X> { } struct S { A a; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,9): error CS0104: 'A' is an ambiguous reference between 'n1.A' and 'n3.n2.A' // A a; Diagnostic(ErrorCode.ERR_AmbigContext, "A").WithArguments("A", "n1.A", "n3.n2.A").WithLocation(22, 9), // (16,25): error CS0104: 'IGoo<>' is an ambiguous reference between 'n1.IGoo<T>' and 'n3.n2.IGoo<V>' // public class C<X> : IGoo<X> Diagnostic(ErrorCode.ERR_AmbigContext, "IGoo<X>").WithArguments("IGoo<>", "n1.IGoo<T>", "n3.n2.IGoo<V>").WithLocation(16, 25), // (22,11): warning CS0169: The field 'S.a' is never used // A a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("n3.S.a").WithLocation(22, 11) ); var ns3 = comp.SourceModule.GlobalNamespace.GetMember<NamespaceSymbol>("n3"); var classC = ns3.GetMember<NamedTypeSymbol>("C"); var classCInterface = classC.Interfaces().Single(); Assert.Equal("IGoo", classCInterface.Name); Assert.Equal(TypeKind.Error, classCInterface.TypeKind); var structS = ns3.GetMember<NamedTypeSymbol>("S"); var structSField = structS.GetMember<FieldSymbol>("a"); Assert.Equal("A", structSField.Type.Name); Assert.Equal(TypeKind.Error, structSField.Type.TypeKind); } [Fact] public void CS0106ERR_BadMemberFlag01() { var text = @"namespace MyNamespace { interface I { void m(); static public void f(); } public class MyClass { virtual ushort field; public void I.m() // CS0106 { } } }"; CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (11,24): error CS0106: The modifier 'virtual' is not valid for this item // virtual ushort field; Diagnostic(ErrorCode.ERR_BadMemberFlag, "field").WithArguments("virtual").WithLocation(11, 24), // (12,23): error CS0106: The modifier 'public' is not valid for this item // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_BadMemberFlag, "m").WithArguments("public").WithLocation(12, 23), // (12,21): error CS0540: 'MyClass.I.m()': containing type does not implement interface 'I' // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("MyNamespace.MyClass.MyNamespace.I.m()", "MyNamespace.I").WithLocation(12, 21), // (11,24): warning CS0169: The field 'MyClass.field' is never used // virtual ushort field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("MyNamespace.MyClass.field").WithLocation(11, 24), // (6,28): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "f").WithArguments("static", "7.0", "8.0").WithLocation(6, 28), // (6,28): error CS8503: The modifier 'public' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "f").WithArguments("public", "7.0", "8.0").WithLocation(6, 28), // (6,28): error CS0501: 'I.f()' must declare a body because it is not marked abstract, extern, or partial // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "f").WithArguments("MyNamespace.I.f()").WithLocation(6, 28) ); } [Fact] public void CS0106ERR_BadMemberFlag02() { var text = @"interface I { public static int P1 { get; } abstract int P2 { static set; } int P4 { new abstract get; } int P5 { static set; } int P6 { sealed get; } } class C { public int P1 { virtual get { return 0; } } internal int P2 { static set { } } static int P3 { new get { return 0; } } int P4 { sealed get { return 0; } } protected internal object P5 { get { return null; } extern set; } public extern object P6 { get; } // no error } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (3,23): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "P1").WithArguments("static", "7.0", "8.0").WithLocation(3, 23), // (3,23): error CS8503: The modifier 'public' is not valid for this item in C# 7. Please use language version '8.0' or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "P1").WithArguments("public", "7.0", "8.0").WithLocation(3, 23), // (3,28): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "get").WithArguments("default interface implementation", "8.0").WithLocation(3, 28), // (4,18): error CS8503: The modifier 'abstract' is not valid for this item in C# 7. Please use language version '8.0' or greater. // abstract int P2 { static set; } Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "P2").WithArguments("abstract", "7.0", "8.0").WithLocation(4, 18), // (4,30): error CS0106: The modifier 'static' is not valid for this item // abstract int P2 { static set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(4, 30), // (5,27): error CS0106: The modifier 'abstract' is not valid for this item // int P4 { new abstract get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("abstract").WithLocation(5, 27), // (5,27): error CS0106: The modifier 'new' is not valid for this item // int P4 { new abstract get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("new").WithLocation(5, 27), // (6,21): error CS0106: The modifier 'static' is not valid for this item // int P5 { static set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(6, 21), // (7,21): error CS0106: The modifier 'sealed' is not valid for this item // int P6 { sealed get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("sealed").WithLocation(7, 21), // (11,29): error CS0106: The modifier 'virtual' is not valid for this item // public int P1 { virtual get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("virtual").WithLocation(11, 29), // (12,30): error CS0106: The modifier 'static' is not valid for this item // internal int P2 { static set { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(12, 30), // (13,25): error CS0106: The modifier 'new' is not valid for this item // static int P3 { new get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("new").WithLocation(13, 25), // (14,21): error CS0106: The modifier 'sealed' is not valid for this item // int P4 { sealed get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("sealed").WithLocation(14, 21), // (15,64): error CS0106: The modifier 'extern' is not valid for this item // protected internal object P5 { get { return null; } extern set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("extern").WithLocation(15, 64), // (16,31): warning CS0626: Method, operator, or accessor 'C.P6.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public extern object P6 { get; } // no error Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P6.get").WithLocation(16, 31) ); } [WorkItem(539584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539584")] [Fact] public void CS0106ERR_BadMemberFlag03() { var text = @" class C { sealed private C() { } new abstract C(object o); public virtual C(C c) { } protected internal override C(int i, int j) { } volatile const int x = 1; } "; CreateCompilation(text).VerifyDiagnostics( // (4,20): error CS0106: The modifier 'sealed' is not valid for this item // sealed private C() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("sealed"), // (5,18): error CS0106: The modifier 'abstract' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,18): error CS0106: The modifier 'new' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("new"), // (6,20): error CS0106: The modifier 'virtual' is not valid for this item // public virtual C(C c) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("virtual"), // (73): error CS0106: The modifier 'override' is not valid for this item // protected internal override C(int i, int j) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("override"), // (8,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile const int x = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile") ); } [Fact] public void CS0106ERR_BadMemberFlag04() { var text = @" class C { static int this[int x] { set { } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 16 }); } [Fact] public void CS0106ERR_BadMemberFlag05() { var text = @" struct Goo { public abstract void Bar1(); public virtual void Bar2() { } public virtual int Bar3 { get;set; } public abstract int Bar4 { get;set; } public abstract event System.EventHandler Bar5; public virtual event System.EventHandler Bar6; // prevent warning for test void OnBar() { Bar6?.Invoke(null, null); } public virtual int this[int x] { get { return 1;} set {;} } // use long for to prevent signature clash public abstract int this[long x] { get; set; } public sealed override string ToString() => null; } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0106: The modifier 'virtual' is not valid for this item // public virtual int Bar3 { get;set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar3").WithArguments("virtual").WithLocation(6, 24), // (7,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int Bar4 { get;set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar4").WithArguments("abstract").WithLocation(7, 25), // (12,24): error CS0106: The modifier 'virtual' is not valid for this item // public virtual int this[int x] { get { return 1;} set {;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual").WithLocation(12, 24), // (14,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[long x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(14, 25), // (5,25): error CS0106: The modifier 'virtual' is not valid for this item // public virtual void Bar2() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar2").WithArguments("virtual").WithLocation(5, 25), // (4,26): error CS0106: The modifier 'abstract' is not valid for this item // public abstract void Bar1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar1").WithArguments("abstract").WithLocation(4, 26), // (8,47): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.EventHandler Bar5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar5").WithArguments("abstract").WithLocation(8, 47), // (9,46): error CS0106: The modifier 'virtual' is not valid for this item // public virtual event System.EventHandler Bar6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar6").WithArguments("virtual").WithLocation(9, 46), // (15,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(15, 35)); } [Fact] public void CS0106ERR_BadMemberFlag06() { var text = @"interface I { int P1 { get; } int P2 { get; set; } } class C : I { private int I.P1 { get { return 0; } } int I.P2 { private get { return 0; } set {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0106: The modifier 'private' is not valid for this item // private int I.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("private").WithLocation(8, 19), // (15,17): error CS0106: The modifier 'private' is not valid for this item // private get { return 0; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(15, 17) ); } [Fact] public void CS0111ERR_MemberAlreadyExists01() { var text = @"class A { void Test() { } public static void Test() { } // CS0111 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MemberAlreadyExists, Line = 4, Column = 24 }); } [Fact] public void CS0111ERR_MemberAlreadyExists02() { var compilation = CreateCompilation( @"static class S { internal static void E<T>(this T t, object o) where T : new() { } internal static void E<T>(this T t, object o) where T : class { } internal static void E<U>(this U u, object o) { } }"); compilation.VerifyDiagnostics( // (4,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(4, 26), // (5,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(5, 26)); } [Fact] public void CS0111ERR_MemberAlreadyExists03() { var compilation = CreateCompilation( @"class C { object this[object o] { get { return null; } set { } } object this[int x] { get { return null; } } int this[int y] { set { } } object this[object o] { get { return null; } set { } } } interface I { object this[int x, int y] { get; set; } I this[int a, int b] { get; } I this[int a, int b] { set; } I this[object a, object b] { get; } }"); compilation.VerifyDiagnostics( // (5,9): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(5, 9), // (6,12): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(6, 12), // (11,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(11, 7), // (12,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(12, 7)); } [Fact] public void CS0111ERR_MemberAlreadyExists04() { var compilation = CreateCompilation( @" using AliasForI = I; public interface I { int this[int x] { get; set; } } public interface J { int this[int x] { get; set; } } public class C : I, J { int I.this[int x] { get { return 0; } set { } } int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 int J.this[int x] { get { return 0; } set { } } //fine public int this[int x] { get { return 0; } set { } } //fine } "); compilation.VerifyDiagnostics( // (13,14): error CS8646: 'I.this[int]' is explicitly implemented more than once. // public class C : I, J Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C").WithArguments("I.this[int]").WithLocation(13, 14), // (16,19): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types // int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C")); } /// <summary> /// Method signature comparison should ignore constraints. /// </summary> [Fact] public void CS0111ERR_MemberAlreadyExists05() { var compilation = CreateCompilation( @"class C { void M<T>(T t) where T : new() { } void M<U>(U u) where U : struct { } void M<T>(T t) where T : C { } } interface I<T> { void M<U>(); void M<U>() where U : T; }"); compilation.VerifyDiagnostics( // (4,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(4, 10), // (5,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(5, 10), // (10,10): error CS0111: Type 'I<T>' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "I<T>").WithLocation(10, 10)); } [Fact] public void CS0112ERR_StaticNotVirtual01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); } public class MyClass2 : MyClass { override public static void MyMethod() // CS0112, remove static keyword { } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 9, Column = 37 }); } [Fact] public void CS0112ERR_StaticNotVirtual02() { var text = @"abstract class A { protected abstract object P { get; } } class B : A { protected static override object P { get { return null; } } public static virtual object Q { get; } internal static abstract object R { get; set; } } "; var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); CreateCompilation(tree).VerifyDiagnostics( // (78): error CS0112: A static member 'B.P' cannot be marked as override, virtual, or abstract // protected static override object P { get { return null; } } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P").WithArguments("B.P").WithLocation(7, 38), // (8,34): error CS0112: A static member 'B.Q' cannot be marked as override, virtual, or abstract // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "Q").WithArguments("B.Q").WithLocation(8, 34), // (8,34): error CS8026: Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater. // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "Q").WithArguments("readonly automatically implemented properties", "6").WithLocation(8, 34), // (9,37): error CS0112: A static member 'B.R' cannot be marked as override, virtual, or abstract // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "R").WithArguments("B.R").WithLocation(9, 37), // (9,41): error CS0513: 'B.R.get' is abstract but it is contained in non-abstract class 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("B.R.get", "B").WithLocation(9, 41), // (9,46): error CS0513: 'B.R.set' is abstract but it is contained in non-abstract class 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("B.R.set", "B").WithLocation(9, 46)); } [Fact] public void CS0112ERR_StaticNotVirtual03() { var text = @"abstract class A { protected abstract event System.Action P; } abstract class B : A { protected static override event System.Action P; public static virtual event System.Action Q; internal static abstract event System.Action R; } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 7, Column = 51 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 8, Column = 47 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 9, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedEvent, Line = 7, Column = 51, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedEvent, Line = 8, Column = 47, IsWarning = true }); } [Fact] public void CS0113ERR_OverrideNotNew01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); public abstract void MyMethod(int x); public virtual void MyMethod(int x, long j) { } } public class MyClass2 : MyClass { override new public void MyMethod() // CS0113, remove new keyword { } virtual override public void MyMethod(int x) // CS0113, remove virtual keyword { } virtual override public void MyMethod(int x, long j) // CS0113, remove virtual keyword { } public static int Main() { return 0; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 14, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 17, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 20, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew02() { var text = @"abstract class A { protected abstract object P { get; } internal virtual object Q { get; set; } } class B : A { protected new override object P { get { return null; } } internal virtual override object Q { get; set; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 8, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 9, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew03() { var text = @"abstract class A { protected abstract event System.Action P; internal virtual event System.Action Q; } class B : A { protected new override event System.Action P; internal virtual override event System.Action Q; } "; CreateCompilation(text).VerifyDiagnostics( // (9,51): error CS0113: A member 'B.Q' marked as override cannot be marked as new or virtual // internal virtual override event System.Action Q; Diagnostic(ErrorCode.ERR_OverrideNotNew, "Q").WithArguments("B.Q").WithLocation(9, 51), // (8,48): error CS0113: A member 'B.P' marked as override cannot be marked as new or virtual // protected new override event System.Action P; Diagnostic(ErrorCode.ERR_OverrideNotNew, "P").WithArguments("B.P").WithLocation(8, 48), // (8,48): warning CS0067: The event 'B.P' is never used // protected new override event System.Action P; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P").WithArguments("B.P").WithLocation(8, 48), // (9,51): warning CS0067: The event 'B.Q' is never used // internal virtual override event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("B.Q").WithLocation(9, 51), // (4,42): warning CS0067: The event 'A.Q' is never used // internal virtual event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("A.Q").WithLocation(4, 42)); } [Fact] public void CS0115ERR_OverrideNotExpected() { var text = @"namespace MyNamespace { abstract public class MyClass1 { public abstract int f(); } abstract public class MyClass2 { public override int f() // CS0115 { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 29 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0118ERR_BadSKknown01() { var text = @"namespace NS { namespace Goo {} internal struct S { void Goo(Goo f) {} } class Bar { Goo foundNamespaceInsteadOfType; } public class A : Goo {} }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,18): error CS0118: 'Goo' is a namespace but is used like a type // void Goo(Goo f) {} Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (12,9): error CS0118: 'Goo' is a namespace but is used like a type // Goo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (15,22): error CS0118: 'Goo' is a namespace but is used like a type // public class A : Goo {} Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (12,13): warning CS0169: The field 'NS.Bar.foundNamespaceInsteadOfType' is never used // Goo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.WRN_UnreferencedField, "foundNamespaceInsteadOfType").WithArguments("NS.Bar.foundNamespaceInsteadOfType") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = ns.GetTypeMembers("A").Single().BaseType(); Assert.Equal("Goo", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); Assert.Null(baseType.BaseType()); var type2 = ns.GetTypeMembers("Bar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers("foundNamespaceInsteadOfType").Single() as FieldSymbol; Assert.Equal("Goo", mem1.Type.Name); Assert.Equal(TypeKind.Error, mem1.Type.TypeKind); var type3 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type3.GetMembers("Goo").Single() as MethodSymbol; var param = mem2.Parameters[0]; Assert.Equal("Goo", param.Type.Name); Assert.Equal(TypeKind.Error, param.Type.TypeKind); } [WorkItem(538147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538147")] [Fact] public void CS0118ERR_BadSKknown02() { var text = @" class Test { static void Main() { B B = null; if (B == B) {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadSKknown, Line = 6, Column = 10 }); } [Fact] public void CS0119ERR_BadSKunknown01() { var text = @"namespace NS { using System; public class Test { public static void F() { } public static int Main() { Console.WriteLine(F.x); return NS(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (10,31): error CS0119: 'NS.Test.F()' is a method, which is not valid in the given context // Console.WriteLine(F.x); Diagnostic(ErrorCode.ERR_BadSKunknown, "F").WithArguments("NS.Test.F()", "method"), // (11,20): error CS0118: 'NS' is a namespace but is used like a variable // return NS(); Diagnostic(ErrorCode.ERR_BadSKknown, "NS").WithArguments("NS", "namespace", "variable") ); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214")] public void CS0119ERR_BadSKunknown02() { var text = @"namespace N1 { class Test { static void Main() { double x = -5d; int y = (global::System.Int32) +x; short z = (System.Int16) +x; } } } "; // Roslyn gives same error twice CreateCompilation(text).VerifyDiagnostics( // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type") ); } [Fact] public void CS0132ERR_StaticConstParam01() { var text = @"namespace NS { struct S { static S(string s) { } } public class clx { static clx(params long[] ary) { } static clx(ref int n) { } } public class cly : clx { static cly() { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 10, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 11, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(539627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539627")] [Fact] public void CS0136ERR_LocalIllegallyOverrides() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @" class MyClass { public MyClass(int a) { long a; // 0136 } public long MyMeth(string x) { long x = 1; // 0136 return x; } public byte MyProp { set { int value; // 0136 } } } "; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "a").WithArguments("a"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "value").WithArguments("value") ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @"class C { public static void Main() { foreach (var x in ""abc"") { int x = 1 ; System.Console.WriteLine(x); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x")); } [Fact] public void CS0138ERR_BadUsingNamespace01() { var text = @"using System.Object; namespace NS { using NS.S; struct S {} }"; var comp = CreateCompilation(Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); comp.VerifyDiagnostics( // (1,7): error CS0138: A using namespace directive can only be applied to namespaces; 'object' is a type not a namespace // using System.Object; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System.Object").WithArguments("object"), // (5,11): error CS0138: A using namespace directive can only be applied to namespaces; 'NS.S' is a type not a namespace // using NS.S; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "NS.S").WithArguments("NS.S"), // (1,1): info CS8019: Unnecessary using directive. // using System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Object;"), // (5,5): info CS8019: Unnecessary using directive. // using NS.S; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NS.S;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Roslyn has 3 extra CS0146, Neal said it's per spec /// </summary> [Fact] public void CS0146ERR_CircularBase01() { var text = @"namespace NS { class A : B { } class B : A { } public class AA : BB { } public class BB : CC { } public class CC : DD { } public class DD : BB { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 3, Column = 11 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 7, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 8, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 9, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = (NamedTypeSymbol)ns.GetTypeMembers("A").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("B", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("DD").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("BB", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("BB").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("CC", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); } [Fact] public void CS0146ERR_CircularBase02() { var text = @"public interface C<T> { } public class D : C<D.Q> { private class Q { } // accessible in base clause } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase03() { var text = @" class A : object, A.IC { protected interface IC { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase04() { var text = @" class A : object, I<A.IC> { protected interface IC { } } interface I<T> { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0179ERR_ExternHasBody01() { var text = @" namespace NS { public class C { extern C() { } extern void M1() { } extern int M2() => 1; extern object P1 { get { return null; } set { } } extern int P2 => 1; extern event System.Action E { add { } remove { } } extern static public int operator + (C c1, C c2) { return 1; } extern static public int operator - (C c1, C c2) => 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,16): error CS0179: 'C.C()' cannot be extern and declare a body // extern C() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "C").WithArguments("NS.C.C()").WithLocation(6, 16), // (7,21): error CS0179: 'C.M1()' cannot be extern and declare a body // extern void M1() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "M1").WithArguments("NS.C.M1()").WithLocation(7, 21), // (8,20): error CS0179: 'C.M2()' cannot be extern and declare a body // extern int M2() => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "M2").WithArguments("NS.C.M2()").WithLocation(8, 20), // (9,28): error CS0179: 'C.P1.get' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("NS.C.P1.get").WithLocation(9, 28), // (9,49): error CS0179: 'C.P1.set' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("NS.C.P1.set").WithLocation(9, 49), // (10,26): error CS0179: 'C.P2.get' cannot be extern and declare a body // extern int P2 => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "1").WithArguments("NS.C.P2.get").WithLocation(10, 26), // (11,40): error CS0179: 'C.E.add' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("NS.C.E.add").WithLocation(11, 40), // (11,48): error CS0179: 'C.E.remove' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("NS.C.E.remove").WithLocation(11, 48), // (12,43): error CS0179: 'C.operator +(C, C)' cannot be extern and declare a body // extern static public int operator + (C c1, C c2) { return 1; } Diagnostic(ErrorCode.ERR_ExternHasBody, "+").WithArguments("NS.C.operator +(NS.C, NS.C)").WithLocation(12, 43), // (13,43): error CS0179: 'C.operator -(C, C)' cannot be extern and declare a body // extern static public int operator - (C c1, C c2) => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "-").WithArguments("NS.C.operator -(NS.C, NS.C)").WithLocation(13, 43)); } [Fact] public void CS0180ERR_AbstractAndExtern01() { CreateCompilation( @"abstract class X { public abstract extern void M(); public extern abstract int P { get; } // If a body is provided for an abstract extern method, // Dev10 reports CS0180, but does not report CS0179/CS0500. public abstract extern void N(int i) { } public extern abstract object Q { set { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("X.M()").WithLocation(3, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("X.P").WithLocation(4, 32), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "N").WithArguments("X.N(int)").WithLocation(7, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "Q").WithArguments("X.Q").WithLocation(8, 35)); } [WorkItem(527618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527618")] [Fact] public void CS0180ERR_AbstractAndExtern02() { CreateCompilation( @"abstract class C { public extern abstract void M(); public extern abstract object P { set; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("C.M()"), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("C.P")); } [Fact] public void CS0180ERR_AbstractAndExtern03() { CreateCompilation( @"class C { public extern abstract event System.Action E; } ") .VerifyDiagnostics( // (3,48): error CS0180: 'C.E' cannot be both extern and abstract // public extern abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E").WithArguments("C.E")); } [Fact] public void CS0181ERR_BadAttributeParamType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1] // Dev11 error public class A1 : Attribute { public A1(dynamic i = null) { } } [A2] // Dev11 ok (bug) public class A2 : Attribute { public A2(dynamic[] i = null) { } } [A3] // Dev11 error (bug) public class A3 : Attribute { public A3(C<dynamic>.D i = 0) { } } [A4] // Dev11 ok public class A4 : Attribute { public A4(C<dynamic>.D[] i = null) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic', which is not a valid attribute parameter type // [A1] // Dev11 error Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A1").WithArguments("i", "dynamic"), // (12,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic[]', which is not a valid attribute parameter type // [A2] // Dev11 ok Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A2").WithArguments("i", "dynamic[]")); } [Fact] public void CS0182ERR_BadAttributeArgument() { var text = @"public class MyClass { static string s = ""Test""; [System.Diagnostics.ConditionalAttribute(s)] // CS0182 void NonConstantArgumentToConditional() { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,46): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [System.Diagnostics.ConditionalAttribute(s)] // CS0182 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s"), // (3,19): warning CS0414: The field 'MyClass.s' is assigned but its value is never used // static string s = "Test"; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("MyClass.s")); } [Fact] public void CS0214ERR_UnsafeNeeded() { var text = @"public struct S { public int a; } public class MyClass { public static void Test() { S s = new S(); S* s2 = &s; // CS0214 s2->a = 3; // CS0214 s.a = 0; } // OK unsafe public static void Test2() { S s = new S(); S* s2 = &s; s2->a = 3; s.a = 0; } } "; // NOTE: only first in scope is reported. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "S*"), // (11,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&s"), // (12,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s2->a = 3; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s2")); } [Fact] public void CS0214ERR_UnsafeNeeded02() { var text = @"unsafe struct S { public fixed int x[10]; } class Program { static void Main() { S s; s.x[1] = s.x[2]; } }"; // NOTE: only first in scope is reported. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x"), // (11,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x")); } [Fact] public void CS0214ERR_UnsafeNeeded03() { var text = @"public struct S { public fixed int buf[10]; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed int buf[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "buf[10]")); } [Fact] public void CS0214ERR_UnsafeNeeded04() { var text = @" namespace System { public class TestType { public void TestMethod() { var x = stackalloc int[10]; // ERROR Span<int> y = stackalloc int[10]; // OK } } } "; CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; // ERROR Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(8, 21)); } [Fact] public void CS0215ERR_OpTFRetType() { var text = @"class MyClass { public static int operator true(MyClass MyInt) // CS0215 { return 1; } public static int operator false(MyClass MyInt) // CS0215 { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,32): error CS0215: The return type of operator True or False must be bool // public static int operator true(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "true"), // (8,32): error CS0215: The return type of operator True or False must be bool // public static int operator false(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "false") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch() { var text = @"class MyClass { // Missing operator false public static bool operator true(MyClass MyInt) // CS0216 { return true; } // Missing matching operator > -- parameter types must match. public static bool operator < (MyClass x, int y) { return false; } // Missing matching operator < -- parameter types must match. public static bool operator > (MyClass x, double y) { return false; } // Missing matching operator >= -- return types must match. public static MyClass operator <=(MyClass x, MyClass y) { return x; } // Missing matching operator <= -- return types must match. public static bool operator >=(MyClass x, MyClass y) { return true; } // Missing operator != public static bool operator ==(MyClass x, MyClass y) { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): warning CS0660: 'MyClass' defines operator == or operator != but does not override Object.Equals(object o) // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "MyClass").WithArguments("MyClass"), // (1,7): warning CS0661: 'MyClass' defines operator == or operator != but does not override Object.GetHashCode() // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "MyClass").WithArguments("MyClass"), // (4,33): error CS0216: The operator 'MyClass.operator true(MyClass)' requires a matching operator 'false' to also be defined // public static bool operator true(MyClass MyInt) // CS0216 Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("MyClass.operator true(MyClass)", "false"), // (73): error CS0216: The operator 'MyClass.operator <(MyClass, int)' requires a matching operator '>' to also be defined // public static bool operator < (MyClass x, int y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<").WithArguments("MyClass.operator <(MyClass, int)", ">"), // (10,33): error CS0216: The operator 'MyClass.operator >(MyClass, double)' requires a matching operator '<' to also be defined // public static bool operator > (MyClass x, double y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">").WithArguments("MyClass.operator >(MyClass, double)", "<"), // (13,36): error CS0216: The operator 'MyClass.operator <=(MyClass, MyClass)' requires a matching operator '>=' to also be defined // public static MyClass operator <=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<=").WithArguments("MyClass.operator <=(MyClass, MyClass)", ">="), // (16,33): error CS0216: The operator 'MyClass.operator >=(MyClass, MyClass)' requires a matching operator '<=' to also be defined // public static bool operator >=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">=").WithArguments("MyClass.operator >=(MyClass, MyClass)", "<="), // (19,33): error CS0216: The operator 'MyClass.operator ==(MyClass, MyClass)' requires a matching operator '!=' to also be defined // public static bool operator ==(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "==").WithArguments("MyClass.operator ==(MyClass, MyClass)", "!=") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch_NoErrorForDynamicObject() { string source = @" using System.Collections.Generic; class C { public static object operator >(C p1, dynamic p2) { return null; } public static dynamic operator <(C p1, object p2) { return null; } public static dynamic operator >=(C p1, dynamic p2) { return null; } public static object operator <=(C p1, object p2) { return null; } public static List<object> operator ==(C p1, dynamic[] p2) { return null; } public static List<dynamic> operator !=(C p1, object[] p2) { return null; } public override bool Equals(object o) { return false; } public override int GetHashCode() { return 1; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0218ERR_MustHaveOpTF() { // Note that the wording of this error has changed. var text = @" public class MyClass { public static MyClass operator &(MyClass f1, MyClass f2) { return new MyClass(); } public static void Main() { MyClass f = new MyClass(); MyClass i = f && f; // CS0218, requires operators true and false } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,21): error CS0218: In order to be applicable as a short circuit operator, the declaring type 'MyClass' of user-defined operator 'MyClass.operator &(MyClass, MyClass)' must declare operator true and operator false. // MyClass i = f && f; // CS0218, requires operators true and false Diagnostic(ErrorCode.ERR_MustHaveOpTF, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)", "MyClass") ); } [Fact] public void CS0224ERR_BadVarargs01() { var text = @"namespace NS { class C { public static void F<T>(T x, __arglist) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 5, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0224ERR_BadVarargs02() { var text = @"class C { C(object o, __arglist) { } // no error void M(__arglist) { } // no error } abstract class C<T> { C(object o) { } // no error C(__arglist) { } void M(object o, __arglist) { } internal abstract object F(__arglist); } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 9, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 10, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 11, Column = 30 }); } [Fact] public void CS0225ERR_ParamsMustBeArray01() { var text = @" using System.Collections.Generic; public class A { struct S { internal List<string> Bar(string s1, params List<string> s2) { return s2; } } public static void Goo(params int a) {} public static int Main() { Goo(1); return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 8, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 13, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; // TODO... } [Fact] public void CS0227ERR_IllegalUnsafe() { var text = @"public class MyClass { unsafe public static void Main() // CS0227 { } } "; var c = CreateCompilation(text, options: TestOptions.ReleaseDll.WithAllowUnsafe(false)); c.VerifyDiagnostics( // (3,31): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe public static void Main() // CS0227 Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Main").WithLocation(3, 31)); } [Fact] public void CS0234ERR_DottedTypeNameNotFoundInNS() { var text = @"using NA = N.A; using NB = C<N.B<object>>; namespace N { } class C<T> { NA a; NB b; N.C<N.D> c; }"; CreateCompilation(text).VerifyDiagnostics( // (2,16): error CS0234: The type or namespace name 'B<>' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NB = C<N.B<object>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "B<object>").WithArguments("B<>", "N").WithLocation(2, 16), // (1,14): error CS0234: The type or namespace name 'A' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NA = N.A; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "A").WithArguments("A", "N").WithLocation(1, 14), // (8,7): error CS0234: The type or namespace name 'C<>' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C<N.D>").WithArguments("C<>", "N").WithLocation(8, 7), // (8,11): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "D").WithArguments("D", "N").WithLocation(8, 11), // (6,8): warning CS0169: The field 'C<T>.a' is never used // NA a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C<T>.a").WithLocation(6, 8), // (7,8): warning CS0169: The field 'C<T>.b' is never used // NB b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b").WithLocation(7, 8), // (8,14): warning CS0169: The field 'C<T>.c' is never used // N.C<N.D> c; Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c").WithLocation(8, 14) ); } [Fact] public void CS0238ERR_SealedNonOverride01() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public sealed void f() // CS0238 { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 24, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 7 }); } [Fact] public void CS0238ERR_SealedNonOverride02() { var text = @"interface I { sealed void M(); sealed object P { get; } } "; //we're diverging from Dev10 - it's a little silly to report two errors saying the same modifier isn't allowed CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (3,17): error CS8503: The modifier 'sealed' is not valid for this item in C# 7. Please use language version '8.0' or greater. // sealed void M(); Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "M").WithArguments("sealed", "7.0", "8.0").WithLocation(3, 17), // (4,19): error CS8503: The modifier 'sealed' is not valid for this item in C# 7. Please use language version '8.0' or greater. // sealed object P { get; } Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "P").WithArguments("sealed", "7.0", "8.0").WithLocation(4, 19), // (4,23): error CS0501: 'I.P.get' must declare a body because it is not marked abstract, extern, or partial // sealed object P { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I.P.get").WithLocation(4, 23), // (3,17): error CS0501: 'I.M()' must declare a body because it is not marked abstract, extern, or partial // sealed void M(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("I.M()").WithLocation(3, 17) ); } [Fact] public void CS0238ERR_SealedNonOverride03() { var text = @"class B { sealed int P { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 3, Column = 16 }); } [Fact] public void CS0238ERR_SealedNonOverride04() { var text = @"class B { sealed event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (3,32): error CS0238: 'B.E' cannot be sealed because it is not an override // sealed event System.Action E; Diagnostic(ErrorCode.ERR_SealedNonOverride, "E").WithArguments("B.E"), // (3,32): warning CS0067: The event 'B.E' is never used // sealed event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B.E")); } [Fact] public void CS0239ERR_CantOverrideSealed() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public override sealed void f() { } } class MyClass3 : MyClass2 { public override void f() // CS0239 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 19, Column = 26 }); } [Fact()] public void CS0243ERR_ConditionalOnOverride() { var text = @"public class MyClass { public virtual void M() { } } public class MyClass2 : MyClass { [System.Diagnostics.ConditionalAttribute(""MySymbol"")] // CS0243 public override void M() { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,6): error CS0243: The Conditional attribute is not valid on 'MyClass2.M()' because it is an override method // [System.Diagnostics.ConditionalAttribute("MySymbol")] // CS0243 Diagnostic(ErrorCode.ERR_ConditionalOnOverride, @"System.Diagnostics.ConditionalAttribute(""MySymbol"")").WithArguments("MyClass2.M()").WithLocation(8, 6)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound01() { var text = @"namespace NS { interface IGoo : INotExist {} // Extra CS0527 interface IBar { string M(ref NoType p1, out NoType p2, params NOType[] ary); } class A : CNotExist {} struct S { public const NoType field = 123; private NoType M() { return null; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 51 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 8, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 11, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 12, Column = 14 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("IGoo").Single() as NamedTypeSymbol; // bug: expected 1 but error symbol // Assert.Equal(1, type1.Interfaces().Count()); var type2 = ns.GetTypeMembers("IBar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers().First() as MethodSymbol; //ErrorTypes now appear as though they are declared in the global namespace. Assert.Equal("System.String NS.IBar.M(ref NoType p1, out NoType p2, params NOType[] ary)", mem1.ToTestDisplayString()); var param = mem1.Parameters[0] as ParameterSymbol; var ptype = param.TypeWithAnnotations; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal(TypeKind.Error, ptype.Type.TypeKind); Assert.Equal("NoType", ptype.Type.Name); var type3 = ns.GetTypeMembers("A").Single() as NamedTypeSymbol; var base1 = type3.BaseType(); Assert.Null(base1.BaseType()); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("CNotExist", base1.Name); var type4 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type4.GetMembers("field").First() as FieldSymbol; Assert.Equal(TypeKind.Error, mem2.Type.TypeKind); Assert.Equal("NoType", mem2.Type.Name); var mem3 = type4.GetMembers("M").Single() as MethodSymbol; Assert.Equal(TypeKind.Error, mem3.ReturnType.TypeKind); Assert.Equal("NoType", mem3.ReturnType.Name); } [WorkItem(537882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537882")] [Fact] public void CS0246ERR_SingleTypeNameNotFound02() { var text = @"using NoExistNS1; namespace NS { using NoExistNS2; // No error for this one class Test { static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): error CS0246: The type or namespace name 'NoExistNS1' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS1").WithArguments("NoExistNS1"), // (5,11): error CS0246: The type or namespace name 'NoExistNS2' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS2").WithArguments("NoExistNS2"), // (1,1): info CS8019: Unnecessary using directive. // using NoExistNS1; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS1;"), // (5,5): info CS8019: Unnecessary using directive. // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS2;")); } [Fact] public void CS0246ERR_SingleTypeNameNotFound03() { var text = @"[Attribute] class C { } "; CreateCompilation(text).VerifyDiagnostics( // (1,2): error CS0246: The type or namespace name 'AttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [Attribute] class C { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("AttributeAttribute").WithLocation(1, 2), // (1,2): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // [Attribute] class C { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute").WithLocation(1, 2)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound04() { var text = @"class AAttribute : System.Attribute { } class BAttribute : System.Attribute { } [A][@B] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 5 }); } [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { var text = @"class C { static void Main(string[] args) { System.Console.WriteLine(typeof(s)); // Invalid } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "s").WithArguments("s")); } [WorkItem(543791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543791")] [Fact] public void CS0246ERR_SingleTypeNameNotFound06() { var text = @"class C { public static Nada x = null, y = null; } "; CreateCompilation(text).VerifyDiagnostics( // (3,19): error CS0246: The type or namespace name 'Nada' could not be found (are you missing a using directive or an assembly reference?) // public static Nada x = null, y = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nada").WithArguments("Nada") ); } [Fact] public void CS0249ERR_OverrideFinalizeDeprecated() { var text = @"class MyClass { protected override void Finalize() // CS0249 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,29): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (3,29): error CS0249: Do not override object.Finalize. Instead, provide a destructor. Diagnostic(ErrorCode.ERR_OverrideFinalizeDeprecated, "Finalize")); } [Fact] public void CS0260ERR_MissingPartial01() { var text = @"namespace NS { public class C // CS0260 { partial struct S { } struct S { } // CS0260 } public partial class C {} public partial class C {} partial interface I {} interface I { } // CS0260 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 3, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 6, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 13, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0261ERR_PartialTypeKindConflict01() { var text = @"namespace NS { partial class A { } partial class A { } partial struct A { } // CS0261 partial interface A { } // CS0261 partial class B { } partial struct B<T> { } partial interface B<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 5, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 6, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0262ERR_PartialModifierConflict01() { var text = @"namespace NS { public partial interface I { } internal partial interface I { } partial interface I { } class A { internal partial class C { } protected partial class C {} private partial struct S { } internal partial struct S { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,30): error CS0262: Partial declarations of 'I' have conflicting accessibility modifiers // public partial interface I { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "I").WithArguments("NS.I").WithLocation(3, 30), // (9,32): error CS0262: Partial declarations of 'A.C' have conflicting accessibility modifiers // internal partial class C { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "C").WithArguments("NS.A.C").WithLocation(9, 32), // (12,32): error CS0262: Partial declarations of 'A.S' have conflicting accessibility modifiers // private partial struct S { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "S").WithArguments("NS.A.S").WithLocation(12, 32) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0263ERR_PartialMultipleBases01() { var text = @"namespace NS { class B1 { } class B2 { } partial class C : B1 // CS0263 - is the base class B1 or B2? { } partial class C : B2 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 5, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; var base1 = type1.BaseType(); Assert.Null(base1.BaseType()); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("B1", base1.Name); } [Fact] public void ERRMixed_BaseAnalysisMishmash() { var text = @"namespace NS { public interface I { } public class C { } public class D { } public struct S { } public struct N0 : object, NS.C { } public class N1 : C, D { } public struct N2 : C, D { } public class N3 : I, C { } public partial class N4 : C { } public partial class N4 : D { } class N5<T> : C, D { } class N6<T> : C, T { } class N7<T> : T, C { } interface N8 : I, I { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 10, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 13, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 16, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 17, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 18, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 18, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 20, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0264ERR_PartialWrongTypeParams01() { var text = @"namespace NS { public partial class C<T1> // CS0264.cs { } partial class C<T2> { partial struct S<X> { } // CS0264.cs partial struct S<T2> { } } internal partial interface IGoo<T, V> { } // CS0264.cs partial interface IGoo<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 3, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 9, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 13, Column = 32 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; Assert.Equal(1, type1.TypeParameters.Length); var param = type1.TypeParameters[0]; // Assert.Equal(TypeKind.Error, param.TypeKind); // this assert it incorrect: it is definitely a type parameter Assert.Equal("T1", param.Name); } [Fact] public void PartialMethodRenameTypeParameters() { var text = @"namespace NS { public partial class MyClass { partial void F<T, U>(T t) where T : class; partial void F<U, T>(U u) where U : class {} } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("MyClass").Single() as NamedTypeSymbol; Assert.Equal(0, type1.TypeParameters.Length); var f = type1.GetMembers("F").Single() as MethodSymbol; Assert.Equal(2, f.TypeParameters.Length); var param1 = f.TypeParameters[0]; var param2 = f.TypeParameters[1]; Assert.Equal("T", param1.Name); Assert.Equal("U", param2.Name); } [Fact] public void CS0265ERR_PartialWrongConstraints01() { var text = @"interface IA<T> { } interface IB { } // Different constraints. partial class A1<T> where T : struct { } partial class A1<T> where T : class { } partial class A2<T, U> where T : struct where U : IA<T> { } partial class A2<T, U> where T : class where U : IB { } partial class A3<T> where T : IA<T> { } partial class A3<T> where T : IA<IA<T>> { } partial interface A4<T> where T : struct, IB { } partial interface A4<T> where T : class, IB { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IB, new() { } // Additional constraints. partial class B1<T> where T : new() { } partial class B1<T> where T : class, new() { } partial class B2<T, U> where T : IA<T> { } partial class B2<T, U> where T : IB, IA<T> { } // Missing constraints. partial interface C1<T> where T : class, new() { } partial interface C1<T> where T : new() { } partial struct C2<T, U> where U : IB, IA<T> { } partial struct C2<T, U> where U : IA<T> { } // Same constraints, different order. partial class D1<T> where T : IA<T>, IB { } partial class D1<T> where T : IB, IA<T> { } partial class D1<T> where T : IA<T>, IB { } partial class D2<T, U, V> where V : T, U { } partial class D2<T, U, V> where V : U, T { } // Different constraint clauses. partial class E1<T, U> where U : T { } partial class E1<T, U> where T : class { } partial class E1<T, U> where U : T { } partial class E2<T, U> where U : IB { } partial class E2<T, U> where T : IA<U> { } partial class E2<T, U> where T : IA<U> { } // Additional constraint clause. partial class F1<T> { } partial class F1<T> { } partial class F1<T> where T : class { } partial class F2<T> { } partial class F2<T, U> where T : class { } partial class F2<T, U> where T : class where U : T { } // Missing constraint clause. partial interface G1<T> where T : class { } partial interface G1<T> { } partial struct G2<T, U> where T : class where U : T { } partial struct G2<T, U> where T : class { } partial struct G2<T, U> { } // Same constraint clauses, different order. partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where U : T where T : class { } partial class H2<T, U, V> where U : IB where T : IA<V> { } partial class H2<T, U, V> where T : IA<V> where U : IB { }"; CreateCompilation(text).VerifyDiagnostics( // (4,15): error CS0265: Partial declarations of 'A1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A1").WithArguments("A1<T>", "T").WithLocation(4, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "T").WithLocation(6, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "U").WithLocation(6, 15), // (8,15): error CS0265: Partial declarations of 'A3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A3").WithArguments("A3<T>", "T").WithLocation(8, 15), // (10,19): error CS0265: Partial declarations of 'A4<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A4").WithArguments("A4<T>", "T").WithLocation(10, 19), // (12,16): error CS0265: Partial declarations of 'A5<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A5").WithArguments("A5<T>", "T").WithLocation(12, 16), // (16,15): error CS0265: Partial declarations of 'B1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B1").WithArguments("B1<T>", "T").WithLocation(16, 15), // (18,15): error CS0265: Partial declarations of 'B2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B2").WithArguments("B2<T, U>", "T").WithLocation(18, 15), // (21,19): error CS0265: Partial declarations of 'C1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C1").WithArguments("C1<T>", "T").WithLocation(21, 19), // (23,16): error CS0265: Partial declarations of 'C2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C2").WithArguments("C2<T, U>", "U").WithLocation(23, 16), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "T").WithLocation(32, 15), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "U").WithLocation(32, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "T").WithLocation(35, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "U").WithLocation(35, 15), // (43,15): error CS0265: Partial declarations of 'F2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "F2").WithArguments("F2<T, U>", "U").WithLocation(43, 15), // (48,16): error CS0265: Partial declarations of 'G2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "G2").WithArguments("G2<T, U>", "U").WithLocation(48, 16)); } [Fact] public void CS0265ERR_PartialWrongConstraints02() { var text = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class B1<T> where T : A, IB<IA> { } partial class B1<T> where T : N.A, N.IB<N.IA> { } partial class B1<T> where T : NA1, NIBA { } partial class B2<T> where T : NA1, IB<A.IC> { } partial class B2<T> where T : NA2, NIBAC { } partial class B3<T> where T : IB<A> { } partial class B3<T> where T : NIBA { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,19): error CS0265: Partial declarations of 'N.B3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B3").WithArguments("N.B3<T>", "T").WithLocation(19, 19), // (1,1): info CS8019: Unnecessary using directive. // using NIA = N.IA; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NIA = N.IA;").WithLocation(1, 1)); } /// <summary> /// Class1.dll: error CS0268: Imported type 'C1' is invalid. It contains a circular base class dependency. /// </summary> [Fact()] public void CS0268ERR_ImportedCircularBase01() { var text = @"namespace NS { public class C3 : C1 { } public interface I3 : I1 { } } "; var ref1 = TestReferences.SymbolsTests.CyclicInheritance.Class1; var ref2 = TestReferences.SymbolsTests.CyclicInheritance.Class2; var comp = CreateCompilation(text, new[] { ref1, ref2 }); comp.VerifyDiagnostics( // (3,23): error CS0268: Imported type 'C2' is invalid. It contains a circular base class dependency. // public class C3 : C1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "C1").WithArguments("C2", "C1"), // (4,22): error CS0268: Imported type 'I2' is invalid. It contains a circular base class dependency. // public interface I3 : I1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "I3").WithArguments("I2", "I1") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0273ERR_InvalidPropertyAccessMod() { var text = @"class C { public object P1 { get; public set; } // CS0273 public object P2 { get; internal set; } public object P3 { get; protected set; } public object P4 { get; protected internal set; } public object P5 { get; private set; } internal object Q1 { public get; set; } // CS0273 internal object Q2 { internal get; set; } // CS0273 internal object Q3 { protected get; set; } // CS0273 internal object Q4 { protected internal get; set; } // CS0273 internal object Q5 { private get; set; } protected object R1 { get { return null; } public set { } } // CS0273 protected object R2 { get { return null; } internal set { } } // CS0273 protected object R3 { get { return null; } protected set { } } // CS0273 protected object R4 { get { return null; } protected internal set { } } // CS0273 protected object R5 { get { return null; } private set { } } protected internal object S1 { get { return null; } public set { } } // CS0273 protected internal object S2 { get { return null; } internal set { } } protected internal object S3 { get { return null; } protected set { } } protected internal object S4 { get { return null; } protected internal set { } } // CS0273 protected internal object S5 { get { return null; } private set { } } private object T1 { public get; set; } // CS0273 private object T2 { internal get; set; } // CS0273 private object T3 { protected get; set; } // CS0273 private object T4 { protected internal get; set; } // CS0273 private object T5 { private get; set; } // CS0273 object U1 { public get; set; } // CS0273 object U2 { internal get; set; } // CS0273 object U3 { protected get; set; } // CS0273 object U4 { protected internal get; set; } // CS0273 object U5 { private get; set; } // CS0273 } "; CreateCompilation(text).VerifyDiagnostics( // (3,36): error CS0273: The accessibility modifier of the 'C.P1.set' accessor must be more restrictive than the property or indexer 'C.P1' // public object P1 { get; public set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.P1.set", "C.P1"), // (8,33): error CS0273: The accessibility modifier of the 'C.Q1.get' accessor must be more restrictive than the property or indexer 'C.Q1' // internal object Q1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q1.get", "C.Q1"), // (9,35): error CS0273: The accessibility modifier of the 'C.Q2.get' accessor must be more restrictive than the property or indexer 'C.Q2' // internal object Q2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q2.get", "C.Q2"), // (10,36): error CS0273: The accessibility modifier of the 'C.Q3.get' accessor must be more restrictive than the property or indexer 'C.Q3' // internal object Q3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q3.get", "C.Q3"), // (11,45): error CS0273: The accessibility modifier of the 'C.Q4.get' accessor must be more restrictive than the property or indexer 'C.Q4' // internal object Q4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q4.get", "C.Q4"), // (13,55): error CS0273: The accessibility modifier of the 'C.R1.set' accessor must be more restrictive than the property or indexer 'C.R1' // protected object R1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R1.set", "C.R1"), // (14,57): error CS0273: The accessibility modifier of the 'C.R2.set' accessor must be more restrictive than the property or indexer 'C.R2' // protected object R2 { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R2.set", "C.R2"), // (15,58): error CS0273: The accessibility modifier of the 'C.R3.set' accessor must be more restrictive than the property or indexer 'C.R3' // protected object R3 { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R3.set", "C.R3"), // (16,67): error CS0273: The accessibility modifier of the 'C.R4.set' accessor must be more restrictive than the property or indexer 'C.R4' // protected object R4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R4.set", "C.R4"), // (18,64): error CS0273: The accessibility modifier of the 'C.S1.set' accessor must be more restrictive than the property or indexer 'C.S1' // protected internal object S1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S1.set", "C.S1"), // (21,76): error CS0273: The accessibility modifier of the 'C.S4.set' accessor must be more restrictive than the property or indexer 'C.S4' // protected internal object S4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S4.set", "C.S4"), // (23,32): error CS0273: The accessibility modifier of the 'C.T1.get' accessor must be more restrictive than the property or indexer 'C.T1' // private object T1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T1.get", "C.T1"), // (24,34): error CS0273: The accessibility modifier of the 'C.T2.get' accessor must be more restrictive than the property or indexer 'C.T2' // private object T2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T2.get", "C.T2"), // (25,35): error CS0273: The accessibility modifier of the 'C.T3.get' accessor must be more restrictive than the property or indexer 'C.T3' // private object T3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T3.get", "C.T3"), // (26,44): error CS0273: The accessibility modifier of the 'C.T4.get' accessor must be more restrictive than the property or indexer 'C.T4' // private object T4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T4.get", "C.T4"), // (273): error CS0273: The accessibility modifier of the 'C.T5.get' accessor must be more restrictive than the property or indexer 'C.T5' // private object T5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T5.get", "C.T5"), // (28,24): error CS0273: The accessibility modifier of the 'C.U1.get' accessor must be more restrictive than the property or indexer 'C.U1' // object U1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U1.get", "C.U1"), // (29,26): error CS0273: The accessibility modifier of the 'C.U2.get' accessor must be more restrictive than the property or indexer 'C.U2' // object U2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U2.get", "C.U2"), // (30,27): error CS0273: The accessibility modifier of the 'C.U3.get' accessor must be more restrictive than the property or indexer 'C.U3' // object U3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U3.get", "C.U3"), // (31,36): error CS0273: The accessibility modifier of the 'C.U4.get' accessor must be more restrictive than the property or indexer 'C.U4' // object U4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U4.get", "C.U4"), // (32,25): error CS0273: The accessibility modifier of the 'C.U5.get' accessor must be more restrictive than the property or indexer 'C.U5' // object U5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U5.get", "C.U5")); } [Fact] public void CS0273ERR_InvalidPropertyAccessMod_Indexers() { var text = @"class C { public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 public object this[int x, double y, int z] { get { return null; } internal set { } } public object this[int x, double y, double z] { get { return null; } protected set { } } public object this[double x, int y, int z] { get { return null; } protected internal set { } } public object this[double x, int y, double z] { get { return null; } private set { } } internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 internal object this[char x, int y, char z] { private get { return null; } set { } } protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected object this[long x, int y, long z] { get { return null; } private set { } } protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 protected internal object this[int x, float y, int z] { get { return null; } internal set { } } protected internal object this[int x, float y, float z] { get { return null; } protected set { } } protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected internal object this[float x, int y, float z] { get { return null; } private set { } } private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 } "; CreateCompilation(text).VerifyDiagnostics( // (3,78): error CS0273: The accessibility modifier of the 'C.this[int, int, double].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, double]' // public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, double].set", "C.this[int, int, double]"), // (8,57): error CS0273: The accessibility modifier of the 'C.this[int, int, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, char]' // internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, char].get", "C.this[int, int, char]"), // (9,59): error CS0273: The accessibility modifier of the 'C.this[int, char, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, int]' // internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, int].get", "C.this[int, char, int]"), // (10,61): error CS0273: The accessibility modifier of the 'C.this[int, char, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, char]' // internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, char].get", "C.this[int, char, char]"), // (11,69): error CS0273: The accessibility modifier of the 'C.this[char, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[char, int, int]' // internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[char, int, int].get", "C.this[char, int, int]"), // (13,79): error CS0273: The accessibility modifier of the 'C.this[int, int, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, long]' // protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, long].set", "C.this[int, int, long]"), // (14,81): error CS0273: The accessibility modifier of the 'C.this[int, long, int].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, int]' // protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, int].set", "C.this[int, long, int]"), // (15,83): error CS0273: The accessibility modifier of the 'C.this[int, long, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, long]' // protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, long].set", "C.this[int, long, long]"), // (16,91): error CS0273: The accessibility modifier of the 'C.this[long, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[long, int, int]' // protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[long, int, int].set", "C.this[long, int, int]"), // (18,89): error CS0273: The accessibility modifier of the 'C.this[int, int, float].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, float]' // protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, float].set", "C.this[int, int, float]"), // (21,101): error CS0273: The accessibility modifier of the 'C.this[float, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[float, int, int]' // protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[float, int, int].set", "C.this[float, int, int]"), // (23,58): error CS0273: The accessibility modifier of the 'C.this[int, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, string]' // private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, string].get", "C.this[int, int, string]"), // (24,60): error CS0273: The accessibility modifier of the 'C.this[int, string, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, int]' // private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, int].get", "C.this[int, string, int]"), // (25,64): error CS0273: The accessibility modifier of the 'C.this[int, string, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, string]' // private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, string].get", "C.this[int, string, string]"), // (26,70): error CS0273: The accessibility modifier of the 'C.this[string, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, int]' // private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, int].get", "C.this[string, int, int]"), // (27,62): error CS0273: The accessibility modifier of the 'C.this[string, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, string]' // private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, string].get", "C.this[string, int, string]"), // (28,50): error CS0273: The accessibility modifier of the 'C.this[int, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, object]' // object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, object].get", "C.this[int, int, object]"), // (29,52): error CS0273: The accessibility modifier of the 'C.this[int, object, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, int]' // object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, int].get", "C.this[int, object, int]"), // (30,56): error CS0273: The accessibility modifier of the 'C.this[int, object, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, object]' // object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, object].get", "C.this[int, object, object]"), // (31,62): error CS0273: The accessibility modifier of the 'C.this[object, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, int]' // object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, int].get", "C.this[object, int, int]"), // (32,54): error CS0273: The accessibility modifier of the 'C.this[object, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, object]' // object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, object].get", "C.this[object, int, object]")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods() { var text = @"class C { public int P { protected get; internal set; } internal object Q { private get { return null; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.P' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P").WithArguments("C.P"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.Q' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "Q").WithArguments("C.Q")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods_Indexer() { var text = @"class C { public int this[int x] { protected get { return 0; } internal set { } } internal object this[object x] { private get { return null; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[int]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[int]"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[object]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[object]")); } [Fact] public void CS0275ERR_PropertyAccessModInInterface() { CreateCompilation( @"interface I { object P { get; } // no error int Q { private get; set; } // CS0275 object R { get; internal set; } // CS0275 } ", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (4,21): error CS8503: The modifier 'private' is not valid for this item in C# 7. Please use language version '8.0' or greater. // int Q { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "get").WithArguments("private", "7.0", "8.0").WithLocation(4, 21), // (4,21): error CS0442: 'I.Q.get': abstract properties cannot have private accessors // int Q { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I.Q.get").WithLocation(4, 21), // (5,30): error CS8503: The modifier 'internal' is not valid for this item in C# 7. Please use language version '8.0' or greater. // object R { get; internal set; } // CS0275 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "set").WithArguments("internal", "7.0", "8.0").WithLocation(5, 30) ); } [Fact] public void CS0275ERR_PropertyAccessModInInterface_Indexer() { CreateCompilation( @"interface I { object this[int x] { get; } // no error int this[char x] { private get; set; } // CS0275 object this[string x] { get; internal set; } // CS0275 } ", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (4,32): error CS8503: The modifier 'private' is not valid for this item in C# 7. Please use language version '8.0' or greater. // int this[char x] { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "get").WithArguments("private", "7.0", "8.0").WithLocation(4, 32), // (4,32): error CS0442: 'I.this[char].get': abstract properties cannot have private accessors // int this[char x] { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I.this[char].get").WithLocation(4, 32), // (5,43): error CS8503: The modifier 'internal' is not valid for this item in C# 7. Please use language version '8.0' or greater. // object this[string x] { get; internal set; } // CS0275 Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "set").WithArguments("internal", "7.0", "8.0").WithLocation(5, 43) ); } [WorkItem(538620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538620")] [Fact] public void CS0276ERR_AccessModMissingAccessor() { var text = @"class A { public virtual object P { get; protected set; } } class B : A { public override object P { protected set { } } // no error public object Q { private set { } } // CS0276 protected internal object R { internal get { return null; } } // CS0276 } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.Q': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Q").WithArguments("B.Q"), // (9,31): error CS0276: 'B.R': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "R").WithArguments("B.R")); } [Fact] public void CS0276ERR_AccessModMissingAccessor_Indexer() { var text = @"class A { public virtual object this[int x] { get { return null; } protected set { } } } class B : A { public override object this[int x] { protected set { } } // no error public object this[char x] { private set { } } // CS0276 protected internal object this[string x] { internal get { return null; } } // CS0276 } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.this[char]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[char]"), // (9,31): error CS0276: 'B.this[string]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[string]")); } [Fact] public void CS0277ERR_UnimplementedInterfaceAccessor() { var text = @"public interface MyInterface { int Property { get; set; } } public class MyClass : MyInterface // CS0277 { public int Property { get { return 0; } protected set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceAccessor, Line = 10, Column = 24 }); } [Fact(Skip = "530901"), WorkItem(530901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530901")] public void CS0281ERR_FriendRefNotEqualToThis() { //sn -k CS0281.snk //sn -i CS0281.snk CS0281.snk //sn -pc CS0281.snk key.publickey //sn -tp key.publickey //csc /target:library /keyfile:CS0281.snk class1.cs //csc /target:library /keyfile:CS0281.snk /reference:class1.dll class2.cs //csc /target:library /keyfile:CS0281.snk /reference:class2.dll /out:class1.dll program.cs var text1 = @"public class A { }"; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); var text2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Class1 , PublicKey=abc"")] class B : A { } "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); var text3 = @"using System.Runtime.CompilerServices; [assembly: System.Reflection.AssemblyVersion(""3"")] [assembly: System.Reflection.AssemblyCulture(""en-us"")] [assembly: InternalsVisibleTo(""MyServices, PublicKeyToken=aaabbbcccdddeee"")] class C : B { } public class A { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text3, new ErrorDescription { Code = (int)ErrorCode.ERR_FriendRefNotEqualToThis, Line = 10, Column = 14 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0305ERR_BadArity01() { var text = @"namespace NS { interface I<T, V> { } struct S<T> : I<T> { } class C<T> { } public class Test { //public static int Main() //{ // C c = new C(); // Not in Dev10 // return 1; //} I<T, V, U> M<T, V, U>() { return null; } public I<int> field; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 5, Column = 19 }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 13 }, // Dev10 miss this due to other errors //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 23 }, // Dev10 miss this due to other errors new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 17, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 18, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0306ERR_BadTypeArgument01() { var source = @"using System; class C<T> { static void F<U>() { } static void M(object o) { new C<int*>(); new C<ArgIterator>(); new C<RuntimeArgumentHandle>(); new C<TypedReference>(); F<int*>(); o.E<object, ArgIterator>(); Action a; a = F<RuntimeArgumentHandle>; a = o.E<T, TypedReference>; Console.WriteLine(typeof(TypedReference?)); Console.WriteLine(typeof(Nullable<TypedReference>)); } } static class S { internal static void E<T, U>(this object o) { } } "; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (7,15): error CS0306: The type 'int*' may not be used as a type argument // new C<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0306: The type 'ArgIterator' may not be used as a type argument // new C<ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 15), // (9,15): error CS0306: The type 'RuntimeArgumentHandle' may not be used as a type argument // new C<RuntimeArgumentHandle>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(9, 15), // (10,15): error CS0306: The type 'TypedReference' may not be used as a type argument // new C<TypedReference>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(10, 15), // (11,9): error CS0306: The type 'int*' may not be used as a type argument // F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*").WithLocation(11, 9), // (12,11): error CS0306: The type 'ArgIterator' may not be used as a type argument // o.E<object, ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "E<object, ArgIterator>").WithArguments("System.ArgIterator").WithLocation(12, 11), // (14,13): error CS0306: The type 'RuntimeArgumentHandle' may not be used as a type argument // a = F<RuntimeArgumentHandle>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<RuntimeArgumentHandle>").WithArguments("System.RuntimeArgumentHandle").WithLocation(14, 13), // (15,13): error CS0306: The type 'TypedReference' may not be used as a type argument // a = o.E<T, TypedReference>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "o.E<T, TypedReference>").WithArguments("System.TypedReference").WithLocation(15, 13), // (16,34): error CS0306: The type 'TypedReference' may not be used as a type argument // Console.WriteLine(typeof(TypedReference?)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference?").WithArguments("System.TypedReference").WithLocation(16, 34), // (17,43): error CS0306: The type 'TypedReference' may not be used as a type argument // Console.WriteLine(typeof(Nullable<TypedReference>)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(17, 43)); } /// <summary> /// Bad type arguments for aliases should be reported at the /// alias declaration rather than at the use. (Note: This differs /// from Dev10 which reports errors at the use, with no errors /// reported if there are no uses of the alias.) /// </summary> [Fact] public void CS0306ERR_BadTypeArgument02() { var source = @"using COfObject = C<object>; using COfIntPtr = C<int*>; using COfArgIterator = C<System.ArgIterator>; // unused class C<T> { static void F<U>() { } static void M() { new COfIntPtr(); COfObject.F<int*>(); COfIntPtr.F<object>(); } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (3,7): error CS0306: The type 'ArgIterator' may not be used as a type argument // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfArgIterator").WithArguments("System.ArgIterator").WithLocation(3, 7), // (2,7): error CS0306: The type 'int*' may not be used as a type argument // using COfIntPtr = C<int*>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfIntPtr").WithArguments("int*").WithLocation(2, 7), // (10,19): error CS0306: The type 'int*' may not be used as a type argument // COfObject.F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*").WithLocation(10, 19), // (3,1): hidden CS8019: Unnecessary using directive. // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using COfArgIterator = C<System.ArgIterator>;").WithLocation(3, 1)); } [WorkItem(538157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538157")] [Fact] public void CS0307ERR_TypeArgsNotAllowed() { var text = @"namespace NS { public class Test<T> { internal object field; public int P { get { return 1; } } public static int Main() { Test<int> t = new NS<T>.Test<int>(); var v = t.field<string>; int p = t.P<int>(); if (v == v | p == p | t == t) {} return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,31): error CS0307: The namespace 'NS' cannot be used with type arguments // Test<int> t = new NS<T>.Test<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "NS<T>").WithArguments("NS", "namespace"), // (11,23): error CS0307: The field 'NS.Test<int>.field' cannot be used with type arguments // var v = t.field<string>; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "field<string>").WithArguments("NS.Test<int>.field", "field"), // (12,23): error CS0307: The property 'NS.Test<int>.P' cannot be used with type arguments // int p = t.P<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<int>").WithArguments("NS.Test<int>.P", "property"), // (13,17): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "v == v"), // (13,26): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "p == p"), // (13,35): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (5,25): warning CS0649: Field 'NS.Test<T>.field' is never assigned to, and will always have its default value null // internal object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Test<T>.field", "null") ); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void CS0307ERR_TypeArgsNotAllowed_02() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld<int>); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS0307: The field 'Test.Fld' cannot be used with type arguments // return (int)(Fld<int>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Fld<int>").WithArguments("Test.Fld", "field") ); } [Fact] public void CS0307ERR_TypeArgsNotAllowed_03() { var text = @"class C<T, U> where T : U<T>, new() { static object M() { return new T<U>(); } }"; CreateCompilation(text).VerifyDiagnostics( // (1,25): error CS0307: The type parameter 'U' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "U<T>").WithArguments("U", "type parameter").WithLocation(1, 25), // (5,20): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter").WithLocation(5, 20)); } [Fact] public void CS0308ERR_HasNoTypeVars01() { var text = @"namespace NS { public class Test { public static string F() { return null; } protected void FF(string s) { } public static int Main() { new Test().FF<string, string>(F<int>()); return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 43 }); } [WorkItem(540090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540090")] [Fact] public void CS0308ERR_HasNoTypeVars02() { var text = @" public class NormalType { public static class M2 { public static int F1 = 1; } public static void Test() { int i; i = M2<int>.F1; } public static int Main() { return -1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 8, Column = 13 }); } [Fact] public void CS0400ERR_GlobalSingleTypeNameNotFound01() { var text = @"namespace NS { public class Test { public static int Main() { // global::D d = new global::D(); return 1; } } struct S { global::G field; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,17): error CS0400: The type or namespace name 'G' could not be found in the global namespace (are you missing an assembly reference?) // global::G field; Diagnostic(ErrorCode.ERR_GlobalSingleTypeNameNotFound, "G").WithArguments("G", "<global namespace>"), // (14,19): warning CS0169: The field 'NS.S.field' is never used // global::G field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0405ERR_DuplicateBound() { var source = @"interface IA { } interface IB { } class A { } class B { } class C<T, U> where T : IA, IB, IA where U : A, IA, A { void M<V>() where V : U, IA, U { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0405: Duplicate constraint 'IA' for type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateBound, "IA").WithArguments("IA", "T").WithLocation(6, 23), // (7,22): error CS0405: Duplicate constraint 'A' for type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateBound, "A").WithArguments("A", "U").WithLocation(7, 22), // (9,34): error CS0405: Duplicate constraint 'U' for type parameter 'V' Diagnostic(ErrorCode.ERR_DuplicateBound, "U").WithArguments("U", "V").WithLocation(9, 34)); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } class A { } class B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void CS0409ERR_DuplicateConstraintClause() { var source = @"interface I<T> where T : class where T : struct { void M<U, V>() where U : new() where V : class where U : class where U : I<T>; }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "T").WithArguments("T").WithLocation(3, 11), // (8,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 15), // (9,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(9, 15)); } [Fact] public void CS0415ERR_BadIndexerNameAttr() { var text = @"using System; using System.Runtime.CompilerServices; public interface IA { int this[int index] { get; set; } } public class A : IA { [IndexerName(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } [IndexerName(""Item"")] // CS0415 int P { get; set; } [IndexerName(""Item"")] // CS0592 int f; [IndexerName(""Item"")] // CS0592 void M() { } [IndexerName(""Item"")] // CS0592 event Action E; [IndexerName(""Item"")] // CS0592 class C { } [IndexerName(""Item"")] // CS0592 struct S { } [IndexerName(""Item"")] // CS0592 delegate void D(); } "; CreateCompilation(text).VerifyDiagnostics( // (15,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (22,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (26,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (29,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (32,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (35,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (38,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (41,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (27,9): warning CS0169: The field 'A.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("A.f"), // (33,18): warning CS0067: The event 'A.E' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("A.E")); } [Fact] public void CS0415ERR_BadIndexerNameAttr_Alias() { var text = @" using Alias = System.Runtime.CompilerServices.IndexerNameAttribute; public interface IA { int this[int index] { get; set; } } public class A : IA { [ Alias(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } } "; var compilation = CreateCompilation(text); // NOTE: uses attribute name from syntax. compilation.VerifyDiagnostics( // (11,6): error CS0415: The 'Alias' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, @"Alias").WithArguments("Alias")); // Note: invalid attribute had no effect on metadata name. var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetProperty("IA." + WellKnownMemberNames.Indexer); Assert.Equal("IA.Item", indexer.MetadataName); } [Fact] public void CS0416ERR_AttrArgWithTypeVars() { var text = @"public class MyAttribute : System.Attribute { public MyAttribute(System.Type t) { } } class G<T> { [MyAttribute(typeof(G<T>))] // CS0416 public void F() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttrArgWithTypeVars, Line = 10, Column = 18 }); } [Fact] public void CS0418ERR_AbstractSealedStatic01() { var text = @"namespace NS { public abstract static class C // CS0418 { internal abstract sealed class CC { private static abstract sealed class CCC // CS0418, 0441 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 3, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 5, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 7, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedStaticClass, Line = 7, Column = 50 }); } [Fact] public void CS0423ERR_ComImportWithImpl() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class ImageProperties { public static void Main() // CS0423 { ImageProperties i = new ImageProperties(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,24): error CS0423: Since 'ImageProperties' has the ComImport attribute, 'ImageProperties.Main()' must be extern or abstract // public static void Main() // CS0423 Diagnostic(ErrorCode.ERR_ComImportWithImpl, "Main").WithArguments("ImageProperties.Main()", "ImageProperties").WithLocation(5, 24)); } [Fact] public void CS0424ERR_ComImportWithBase() { var text = @"using System.Runtime.InteropServices; public class A { } [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B : A { } // CS0424 error "; CreateCompilation(text).VerifyDiagnostics( // (5,7): error CS0424: 'B': a class with the ComImport attribute cannot specify a base class // class B : A { } // CS0424 error Diagnostic(ErrorCode.ERR_ComImportWithBase, "B").WithArguments("B").WithLocation(5, 7)); } [WorkItem(856187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/856187")] [WorkItem(866093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866093")] [Fact] public void CS0424ERR_ComImportWithInitializers() { var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B { public static int X = 5; public int Y = 5; public const decimal D = 5; public const int Yconst = 5; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public static int X = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(7, 25), // (9,28): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public const decimal D = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(9, 28), // (8,18): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public int Y = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(8, 18) ); } [Fact] public void CS0425ERR_ImplBadConstraints01() { var source = @"interface IA<T> { } interface IB { } interface I { // Different constraints: void A1<T>() where T : struct; void A2<T, U>() where T : struct where U : IA<T>; void A3<T>() where T : IA<T>; void A4<T, U>() where T : struct, IA<T>; // Additional constraints: void B1<T>(); void B2<T>() where T : new(); void B3<T, U>() where T : IA<T>; // Missing constraints. void C1<T>() where T : class; void C2<T>() where T : class, new(); void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. void D1<T>() where T : IA<T>, IB; void D2<T, U, V>() where V : T, U; // Different constraint clauses. void E1<T, U>() where U : T; // Additional constraint clause. void F1<T, U>() where T : class; // Missing constraint clause. void G1<T, U>() where T : class where U : T; // Same constraint clauses, different order. void H1<T, U>() where T : class where U : T; void H2<T, U>() where T : class where U : T; void H3<T, U, V>() where V : class where U : IB where T : IA<V>; // Different type parameter names. void K1<T, U>() where T : class where U : T; void K2<T, U>() where T : class where U : T; } class C : I { // Different constraints: public void A1<T>() where T : class { } public void A2<T, U>() where T : struct where U : IB { } public void A3<T>() where T : IA<IA<T>> { } public void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: public void B1<T>() where T : new() { } public void B2<T>() where T : class, new() { } public void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. public void C1<T>() { } public void C2<T>() where T : class { } public void C3<T, U>() where U : IA<T> { } // Same constraints, different order. public void D1<T>() where T : IB, IA<T> { } public void D2<T, U, V>() where V : U, T { } // Different constraint clauses. public void E1<T, U>() where T : class { } // Additional constraint clause. public void F1<T, U>() where T : class where U : T { } // Missing constraint clause. public void G1<T, U>() where T : class { } // Same constraint clauses, different order. public void H1<T, U>() where U : T where T : class { } public void H2<T, U>() where U : class where T : U { } public void H3<T, U, V>() where T : IA<V> where U : IB where V : class { } // Different type parameter names. public void K1<U, T>() where T : class where U : T { } public void K2<T1, T2>() where T1 : class where T2 : T1 { } }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilation(source).VerifyDiagnostics( // (38,17): error CS0425: The constraints for type parameter 'T' of method 'C.A1<T>()' must match the constraints for type parameter 'T' of interface method 'I.A1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A1").WithArguments("T", "C.A1<T>()", "T", "I.A1<T>()").WithLocation(38, 17), // (39,17): error CS0425: The constraints for type parameter 'U' of method 'C.A2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.A2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A2").WithArguments("U", "C.A2<T, U>()", "U", "I.A2<T, U>()").WithLocation(39, 17), // (40,17): error CS0425: The constraints for type parameter 'T' of method 'C.A3<T>()' must match the constraints for type parameter 'T' of interface method 'I.A3<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A3").WithArguments("T", "C.A3<T>()", "T", "I.A3<T>()").WithLocation(40, 17), // (41,17): error CS0425: The constraints for type parameter 'T' of method 'C.A4<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.A4<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A4").WithArguments("T", "C.A4<T, U>()", "T", "I.A4<T, U>()").WithLocation(41, 17), // (43,17): error CS0425: The constraints for type parameter 'T' of method 'C.B1<T>()' must match the constraints for type parameter 'T' of interface method 'I.B1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B1").WithArguments("T", "C.B1<T>()", "T", "I.B1<T>()").WithLocation(43, 17), // (44,17): error CS0425: The constraints for type parameter 'T' of method 'C.B2<T>()' must match the constraints for type parameter 'T' of interface method 'I.B2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B2").WithArguments("T", "C.B2<T>()", "T", "I.B2<T>()").WithLocation(44, 17), // (45,17): error CS0425: The constraints for type parameter 'T' of method 'C.B3<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.B3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B3").WithArguments("T", "C.B3<T, U>()", "T", "I.B3<T, U>()").WithLocation(45, 17), // (47,17): error CS0425: The constraints for type parameter 'T' of method 'C.C1<T>()' must match the constraints for type parameter 'T' of interface method 'I.C1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C1").WithArguments("T", "C.C1<T>()", "T", "I.C1<T>()").WithLocation(47, 17), // (48,17): error CS0425: The constraints for type parameter 'T' of method 'C.C2<T>()' must match the constraints for type parameter 'T' of interface method 'I.C2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C2").WithArguments("T", "C.C2<T>()", "T", "I.C2<T>()").WithLocation(48, 17), // (49,17): error CS0425: The constraints for type parameter 'U' of method 'C.C3<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.C3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C3").WithArguments("U", "C.C3<T, U>()", "U", "I.C3<T, U>()").WithLocation(49, 17), // (54,17): error CS0425: The constraints for type parameter 'T' of method 'C.E1<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("T", "C.E1<T, U>()", "T", "I.E1<T, U>()").WithLocation(54, 17), // (54,17): error CS0425: The constraints for type parameter 'U' of method 'C.E1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("U", "C.E1<T, U>()", "U", "I.E1<T, U>()").WithLocation(54, 17), // (56,17): error CS0425: The constraints for type parameter 'U' of method 'C.F1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.F1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "F1").WithArguments("U", "C.F1<T, U>()", "U", "I.F1<T, U>()").WithLocation(56, 17), // (58,17): error CS0425: The constraints for type parameter 'U' of method 'C.G1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.G1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "G1").WithArguments("U", "C.G1<T, U>()", "U", "I.G1<T, U>()").WithLocation(58, 17), // (61,17): error CS0425: The constraints for type parameter 'T' of method 'C.H2<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("T", "C.H2<T, U>()", "T", "I.H2<T, U>()").WithLocation(61, 17), // (61,17): error CS0425: The constraints for type parameter 'U' of method 'C.H2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("U", "C.H2<T, U>()", "U", "I.H2<T, U>()").WithLocation(61, 17), // (64,17): error CS0425: The constraints for type parameter 'U' of method 'C.K1<U, T>()' must match the constraints for type parameter 'T' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("U", "C.K1<U, T>()", "T", "I.K1<T, U>()").WithLocation(64, 17), // (64,17): error CS0425: The constraints for type parameter 'T' of method 'C.K1<U, T>()' must match the constraints for type parameter 'U' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("T", "C.K1<U, T>()", "U", "I.K1<T, U>()").WithLocation(64, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints02() { var source = @"interface IA<T> { } interface IB { } interface I<T> { void M1<U, V>() where U : T where V : IA<T>; void M2<U>() where U : T, new(); } class C1 : I<IB> { public void M1<U, V>() where U : IB where V : IA<IB> { } public void M2<U>() where U : I<IB> { } } class C2<T, U> : I<IA<U>> { public void M1<X, Y>() where Y : IA<IA<U>> where X : IA<U> { } public void M2<X>() where X : T, new() { } }"; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0425: The constraints for type parameter 'U' of method 'C1.M2<U>()' must match the constraints for type parameter 'U' of interface method 'I<IB>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("U", "C1.M2<U>()", "U", "I<IB>.M2<U>()").WithLocation(11, 17), // (16,17): error CS0425: The constraints for type parameter 'X' of method 'C2<T, U>.M2<X>()' must match the constraints for type parameter 'U' of interface method 'I<IA<U>>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("X", "C2<T, U>.M2<X>()", "U", "I<IA<U>>.M2<U>()").WithLocation(16, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints03() { var source = @"interface IA { } class B { } interface I1<T> { void M<U>() where U : struct, T; } class C1<T> : I1<T> where T : struct { public void M<U>() where U : T { } } interface I2<T> { void M<U>() where U : class, T; } class C2 : I2<B> { public void M<U>() where U : B { } } class C2<T> : I2<T> where T : class { public void M<U>() where U : T { } } interface I3<T> { void M<U>() where U : T, new(); } class C3 : I3<B> { public void M<U>() where U : B { } } class C3<T> : I3<T> where T : new() { public void M<U>() where U : T { } } interface I4<T> { void M<U>() where U : T, IA; } class C4 : I4<IA> { public void M<U>() where U : IA { } } class C4<T> : I4<T> where T : IA { public void M<U>() where U : T { } } interface I5<T> { void M<U>() where U : B, T; } class C5 : I5<B> { public void M<U>() where U : B { } } class C5<T> : I5<T> where T : B { public void M<U>() where U : T { } }"; CreateCompilation(source).VerifyDiagnostics( // (9,17): error CS0425: The constraints for type parameter 'U' of method 'C1<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I1<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C1<T>.M<U>()", "U", "I1<T>.M<U>()").WithLocation(9, 17), // (9,19): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 19), // (17,17): error CS0425: The constraints for type parameter 'U' of method 'C2.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2.M<U>()", "U", "I2<B>.M<U>()").WithLocation(17, 17), // (21,17): error CS0425: The constraints for type parameter 'U' of method 'C2<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2<T>.M<U>()", "U", "I2<T>.M<U>()").WithLocation(21, 17), // (29,17): error CS0425: The constraints for type parameter 'U' of method 'C3.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3.M<U>()", "U", "I3<B>.M<U>()").WithLocation(29, 17), // (33,17): error CS0425: The constraints for type parameter 'U' of method 'C3<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3<T>.M<U>()", "U", "I3<T>.M<U>()").WithLocation(33, 17), // (45,17): error CS0425: The constraints for type parameter 'U' of method 'C4<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I4<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C4<T>.M<U>()", "U", "I4<T>.M<U>()").WithLocation(45, 17), // (57,17): error CS0425: The constraints for type parameter 'U' of method 'C5<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I5<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C5<T>.M<U>()", "U", "I5<T>.M<U>()").WithLocation(57, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints04() { var source = @"interface IA { void M1<T>(); void M2<T, U>() where U : T; } interface IB { void M1<T>() where T : IB; void M2<X, Y>(); } abstract class C : IA, IB { public abstract void M1<T>(); public abstract void M2<X, Y>(); }"; CreateCompilation(source).VerifyDiagnostics( // (14,26): error CS0425: The constraints for type parameter 'Y' of method 'C.M2<X, Y>()' must match the constraints for type parameter 'U' of interface method 'IA.M2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("Y", "C.M2<X, Y>()", "U", "IA.M2<T, U>()").WithLocation(14, 26), // (13,26): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "IB.M1<T>()").WithLocation(13, 26)); } [Fact] public void CS0425ERR_ImplBadConstraints05() { var source = @"interface I<T> { } class C { } interface IA<T, U> { void A1<V>() where V : T, I<T>; void A2<V>() where V : T, U, I<T>, I<U>; } interface IB<T> { void B1<U>() where U : C; void B2<U, V>() where U : C, T, V; } class A<T, U> { // More constraints than IA<T, U>.A1<V>(). public void A1<V>() where V : T, U, I<T>, I<U> { } // Fewer constraints than IA<T, U>.A2<V>(). public void A2<V>() where V : T, I<T> { } } class B<T> { // More constraints than IB<T>.B1<U>(). public void B1<U>() where U : C, T { } // Fewer constraints than IB<T>.B2<U, V>(). public void B2<U, V>() where U : T, V { } } class A1<T> : A<T, T>, IA<T, T> { } class A2<T, U> : A<T, U>, IA<T, U> { } class B1 : B<C>, IB<C> { } class B2<T> : B<T>, IB<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (30,27): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A2<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A2<V>()'. Consider using an explicit interface implementation instead. // class A2<T, U> : A<T, U>, IA<T, U> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IA<T, U>").WithArguments("V", "A<T, U>.A2<V>()", "V", "IA<T, U>.A2<V>()").WithLocation(30, 27), // (30,27): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A1<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A1<V>()'. Consider using an explicit interface implementation instead. // class A2<T, U> : A<T, U>, IA<T, U> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IA<T, U>").WithArguments("V", "A<T, U>.A1<V>()", "V", "IA<T, U>.A1<V>()").WithLocation(30, 27), // (36,21): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B2<U, V>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B2<U, V>()'. Consider using an explicit interface implementation instead. // class B2<T> : B<T>, IB<T> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IB<T>").WithArguments("U", "B<T>.B2<U, V>()", "U", "IB<T>.B2<U, V>()").WithLocation(36, 21), // (36,21): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B1<U>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B1<U>()'. Consider using an explicit interface implementation instead. // class B2<T> : B<T>, IB<T> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IB<T>").WithArguments("U", "B<T>.B1<U>()", "U", "IB<T>.B1<U>()").WithLocation(36, 21)); } [Fact] public void CS0425ERR_ImplBadConstraints06() { var source = @"using NIA1 = N.IA; using NIA2 = N.IA; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } class A { } } interface IB { void M1<T>() where T : N.A, N.IA; void M2<T>() where T : NA1, NIA1; } abstract class B1 : IB { public abstract void M1<T>() where T : NA1, NIA1; public abstract void M2<T>() where T : NA2, NIA2; } abstract class B2 : IB { public abstract void M1<T>() where T : NA1; public abstract void M2<T>() where T : NIA2; }"; CreateCompilation(source).VerifyDiagnostics( // (22,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "B2.M1<T>()", "T", "IB.M1<T>()").WithLocation(22, 26), // (23,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M2<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("T", "B2.M2<T>()", "T", "IB.M2<T>()").WithLocation(23, 26)); } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg01() { var text = @"namespace NS { public class C { public interface I { } } struct S { } public class Test { C.I.x field; // CS0426 void M(S.s p) { } // CS0426 public static int Main() { // C.A a; // CS0426 return 1; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,18): error CS0426: The type name 's' does not exist in the type 'NS.S' // void M(S.s p) { } // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "s").WithArguments("s", "NS.S"), // (13,13): error CS0426: The type name 'x' does not exist in the type 'NS.C.I' // C.I.x field; // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "x").WithArguments("x", "NS.C.I"), // (13,15): warning CS0169: The field 'NS.Test.field' is never used // C.I.x field; // CS0426 Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Test.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg02() { var text = @"class A<T> { A<T>.T F = default(A<T>.T); } class B : A<object> { B.T F = default(B.T); }"; CreateCompilation(text).VerifyDiagnostics( // (3,10): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 10), // (3,29): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 29), // (7,7): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 7), // (7,23): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 23)); } [Fact] public void CS0430ERR_BadExternAlias() { var text = @"extern alias MyType; // CS0430 public class Test { public static void Main() {} } public class MyClass { } "; CreateCompilation(text).VerifyDiagnostics( // (1,14): error CS0430: The extern alias 'MyType' was not specified in a /reference option // extern alias MyType; // CS0430 Diagnostic(ErrorCode.ERR_BadExternAlias, "MyType").WithArguments("MyType"), // (1,1): info CS8020: Unused extern alias. // extern alias MyType; // CS0430 Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias MyType;")); } [Fact] public void CS0432ERR_AliasNotFound() { var text = @"class C { public class A { } } class E : C::A { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AliasNotFound, Line = 6, Column = 11 }); } /// <summary> /// Import - same name class from lib1 and lib2 /// </summary> [Fact] public void CS0433ERR_SameFullNameAggAgg01() { var text = @"namespace NS { class Test { Class1 var; void M(Class1 p) {} } } "; var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var ref2 = TestReferences.SymbolsTests.MultiModule.Assembly; // Roslyn give CS0104 for now var comp = CreateCompilation(text, new List<MetadataReference> { ref1, ref2 }); comp.VerifyDiagnostics( // (6,16): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // void M(Class1 p) {} Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,9): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // Class1 var; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,16): warning CS0169: The field 'NS.Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("NS.Test.var")); text = @" class Class1 { } class Test { Class1 var; } "; comp = CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // goo.cs(8,5): warning CS0436: The type 'Class1' in 'goo.cs' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'goo.cs'. // Class1 var; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("goo.cs", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // goo.cs(8,12): warning CS0169: The field 'Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("Test.var") ); } /// <summary> /// import - lib1: namespace A { namespace B { .class C {}.. }} /// vs. lib2: Namespace A { class B { class C{} } }} - use C /// </summary> [Fact] public void CS0434ERR_SameFullNameNsAgg01() { var text = @" namespace NS { public class Test { public static void Main() { // var v = new N1.N2.A(); } void M(N1.N2.A p) { } } } "; var ref1 = TestReferences.DiagnosticTests.ErrTestLib11.dll; var ref2 = TestReferences.DiagnosticTests.ErrTestLib02.dll; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { ref1, ref2 }, // new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 9, Column = 28 }, // Dev10 one error new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 12, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs01() // I (Neal Gafter) was not able to reproduce this in Dev10 using the batch compiler, but the Dev10 // background compiler will emit this diagnostic (along with one other) for this code: // namespace NS { // namespace A { } // public class A { } // } // class B : NS.A { } //Compiling the scenario below using the native compiler gives CS0438 for me (Ed). { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } class Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs03() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs04() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs05() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs06() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0436WRN_SameFullNameThisAggAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util")); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0436WRN_SameFullNameThisAggAgg_02() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0435WRN_SameFullNameThisNsAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0437WRN_SameFullNameThisAggNs_01() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_01() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_03() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (15,15): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_04() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } namespace Util { class A<T> {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }); CompileAndVerify(comp).VerifyDiagnostics(); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_05() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_06() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_07() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_08() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_09() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_10() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_11() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_12() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_13() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_14() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_15() { var mod3Source = @" namespace NS { namespace Util { public class A {} } } "; var mod3Ref = CreateCompilation(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), mod3Ref, s_mod1.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_16() { var mod3Source = @" namespace NS { internal class Util { public class A {} } }"; var mod3Ref = CreateCompilation(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), mod3Ref, s_mod2.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")] public void Bug641639() { var ModuleA01 = @" class A01 { public static int AT = (new { field = 1 }).field; } "; var ModuleA01Ref = CreateCompilation(ModuleA01, options: TestOptions.ReleaseModule, assemblyName: "ModuleA01").EmitToImageReference(); var ModuleB01 = @" class B01{ public static int AT = (new { field = 2 }).field; } "; var ModuleB01Ref = CreateCompilation(ModuleB01, options: TestOptions.ReleaseModule, assemblyName: "ModuleB01").EmitToImageReference(); var text = @" class Test { static void Main() { System.Console.WriteLine(""{0} + {1} = {2}"", A01.AT, A01.AT, B01.AT); A01.AT = B01.AT; System.Console.WriteLine(""{0} = {1}"", A01.AT, B01.AT); } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { ModuleA01Ref, ModuleB01Ref }, TestOptions.ReleaseExe); Assert.Equal(1, comp.Assembly.Modules[1].GlobalNamespace.GetTypeMembers("<ModuleA01>f__AnonymousType0", 1).Length); Assert.Equal(1, comp.Assembly.Modules[2].GlobalNamespace.GetTypeMembers("<ModuleB01>f__AnonymousType0", 1).Length); CompileAndVerify(comp, expectedOutput: @"1 + 1 = 2 2 = 2"); } [Fact] public void NameCollisionWithAddedModule_01() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 "; ImmutableArray<Byte> ilBytes; using (var reference = IlasmUtilities.CreateTempAssembly(ilSource, prependDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var source = @" interface ITest20 {} "; var compilation = CreateCompilation(source, new List<MetadataReference>() { moduleRef }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8004: Type 'ITest20<T>' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("ITest20<T>", "ITest20Mod.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_02() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } "; ImmutableArray<Byte> ilBytes; using (var reference = IlasmUtilities.CreateTempAssembly(ilSource, prependDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var mod2Source = @" namespace ns { public interface c1 {} public interface c3 {} } public interface c2 {} public interface c4 {} namespace ns1 { public interface c5 {} } "; var moduleRef2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "mod_1_2").EmitToImageReference(); var compilation = CreateCompilation("", new List<MetadataReference>() { moduleRef1, moduleRef2 }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8005: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("c2", "mod_1_2.netmodule", "c2<T>", "mod_1_1.netmodule"), // error CS8005: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("ns.c1", "mod_1_2.netmodule", "ns.c1<T>", "mod_1_1.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_03() { var forwardedTypesSource = @" public class CF1 {} namespace ns { public class CF2 { } } public class CF3<T> {} "; var forwardedTypes1 = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes1"); var forwardedTypes1Ref = new CSharpCompilationReference(forwardedTypes1); var forwardedTypes2 = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes2"); var forwardedTypes2Ref = new CSharpCompilationReference(forwardedTypes2); var forwardedTypesModRef = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseModule, assemblyName: "forwardedTypesMod"). EmitToImageReference(); var modSource = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(ns.CF2))] "; var module1_FT1_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module1_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module2_FT1_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module2_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module3_FT2_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module3_FT2", references: new MetadataReference[] { forwardedTypes2Ref }). EmitToImageReference(); var module4_Ref = CreateCompilation("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<int>))]", options: TestOptions.ReleaseModule, assemblyName: "module4_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var compilation = CreateCompilation(forwardedTypesSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8006: Forwarded type 'ns.CF2' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("ns.CF2"), // error CS8006: Forwarded type 'CF1' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("CF1")); compilation = CreateCompilation(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); // Exported types in .NET modules cause PEVerify to fail on some platforms. CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<byte>))]", new List<MetadataReference>() { module4_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes2Ref, new CSharpCompilationReference(forwardedTypes1, aliases: ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); compilation = CreateCompilation( @" extern alias FT1; [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::ns.CF2))] ", new List<MetadataReference>() { forwardedTypesModRef, new CSharpCompilationReference(forwardedTypes1, ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule"), // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { forwardedTypesModRef, module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, forwardedTypesModRef, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, module2_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, module3_FT2_Ref, forwardedTypes1Ref, forwardedTypes2Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void CS0441ERR_SealedStaticClass01() { var text = @"namespace NS { static sealed class Test { public static int Main() { return 1; } } sealed static class StaticClass : Test //verify 'sealed' works { } static class Derived : StaticClass //verify 'sealed' works { // Test tst = new Test(); //verify 'static' works } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,25): error CS0441: 'NS.Test': a class cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "Test").WithArguments("NS.Test"), // (11,25): error CS0441: 'NS.StaticClass': a class cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "StaticClass").WithArguments("NS.StaticClass"), //CONSIDER: Dev10 skips these cascading errors // (11,39): error CS07: Static class 'NS.StaticClass' cannot derive from type 'NS.Test'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Test").WithArguments("NS.StaticClass", "NS.Test"), // (15,28): error CS07: Static class 'NS.Derived' cannot derive from type 'NS.StaticClass'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "StaticClass").WithArguments("NS.Derived", "NS.StaticClass")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0442ERR_PrivateAbstractAccessor() { var source = @"abstract class MyClass { public abstract int P { get; private set; } // CS0442 protected abstract object Q { private get; set; } // CS0442 internal virtual object R { private get; set; } // no error } "; CreateCompilation(source).VerifyDiagnostics( // (3,42): error CS0442: 'MyClass.P.set': abstract properties cannot have private accessors // public abstract int P { get; private set; } // CS0442 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("MyClass.P.set").WithLocation(3, 42), // (4,43): error CS0442: 'MyClass.Q.get': abstract properties cannot have private accessors // protected abstract object Q { private get; set; } // CS0442 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("MyClass.Q.get").WithLocation(4, 43)); } [Fact] public void CS0448ERR_BadIncDecRetType() { // Note that the wording of this error message has changed slightly from the native compiler. var text = @"public struct S { public static S? operator ++(S s) { return new S(); } // CS0448 public static S? operator --(S s) { return new S(); } // CS0448 }"; CreateCompilation(text).VerifyDiagnostics( // (3,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator ++(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "++"), // (4,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator --(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--")); } [Fact] public void CS0450ERR_RefValBoundWithClass() { var source = @"interface I { } class A { } class B<T> { } class C<T1, T2, T3, T4, T5, T6, T7> where T1 : class, I where T2 : struct, I where T3 : class, A where T4 : struct, B<T5> where T6 : class, T5 where T7 : struct, T5 { }"; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS0450: 'A': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "A").WithArguments("A").WithLocation(7, 23), // (8, 24): error CS0450: 'B<T5>': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "B<T5>").WithArguments("B<T5>").WithLocation(8, 24)); } [Fact] public void CS0452ERR_RefConstraintNotSatisfied() { var source = @"interface I { } class A { } class B<T> where T : class { } class C { static void F<U>() where U : class { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>() Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (19,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(19, 15), // (20,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(20, 9), // (24,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (39,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied01() { var source = @"interface I { } class A { } class B<T> where T : struct { } class C { static void F<U>() where U : struct { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (14,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(14, 15), // (15,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(15, 9), // (24,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (34,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(34, 15), // (35,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(35, 9), // (39,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied02() { var source = @"abstract class A<X, Y> { internal static void F<U>() where U : struct { } internal abstract void M<U>() where U : X, Y; } class B1 : A<int?, object> { internal override void M<U>() { F<U>(); } } class B2 : A<object, int?> { internal override void M<U>() { F<U>(); } } class B3 : A<object, int> { internal override void M<U>() { F<U>(); } } class B4<T> : A<object, T> { internal override void M<U>() { F<U>(); } } class B5<T> : A<object, T> where T : struct { internal override void M<U>() { F<U>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<int?, object>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<int?, object>.F<U>()", "U", "U").WithLocation(10, 9), // (17,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, int?>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, int?>.F<U>()", "U", "U").WithLocation(17, 9), // (31,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, T>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, T>.F<U>()", "U", "U").WithLocation(31, 9)); } [Fact] public void CS0454ERR_CircularConstraint01() { var source = @"class A<T> where T : T { } class B<T, U, V> where V : T where U : V where T : U { } delegate void D<T1, T2, T3>() where T1 : T3 where T2 : T2 where T3 : T1;"; CreateCompilation(source).VerifyDiagnostics( // (1,9): error CS0454: Circular constraint dependency involving 'T' and 'T' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(1, 9), // (4,9): error CS0454: Circular constraint dependency involving 'T' and 'V' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "V").WithLocation(4, 9), // (10,17): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(10, 17), // (10,21): error CS0454: Circular constraint dependency involving 'T2' and 'T2' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T2").WithLocation(10, 21)); } [Fact] public void CS0454ERR_CircularConstraint02() { var source = @"interface I { void M<T, U, V>() where T : V, new() where U : class, V where V : U; } class A<T> { } class B<T, U> where T : U where U : A<U>, U { }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0454: Circular constraint dependency involving 'V' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "V").WithArguments("V", "U").WithLocation(3, 18), // (9,12): error CS0454: Circular constraint dependency involving 'U' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(9, 12)); } [Fact] public void CS0454ERR_CircularConstraint03() { var source = @"interface I<T1, T2, T3, T4, T5> where T1 : T2, T4 where T2 : T3 where T3 : T1 where T4 : T5 where T5 : T1 { } class C<T1, T2, T3, T4, T5> where T1 : T2, T3 where T2 : T3, T4 where T3 : T4, T5 where T5 : T2, T3 { } struct S<T1, T2, T3, T4, T5> where T4 : T1 where T5 : T2 where T1 : T3 where T2 : T4 where T3 : T5 { } delegate void D<T1, T2, T3, T4>() where T1 : T2 where T2 : T3, T4 where T3 : T4 where T4 : T2;"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(1, 13), // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T5").WithLocation(1, 13), // (9,13): error CS0454: Circular constraint dependency involving 'T2' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T5").WithLocation(9, 13), // (9,17): error CS0454: Circular constraint dependency involving 'T3' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T3").WithArguments("T3", "T5").WithLocation(9, 17), // (16,10): error CS0454: Circular constraint dependency involving 'T1' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T4").WithLocation(16, 10), // (24,21): error CS0454: Circular constraint dependency involving 'T2' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T4").WithLocation(24, 21)); } [Fact] public void CS0454ERR_CircularConstraint04() { var source = @"interface I<T> where U : U { } class C<T, U> where T : U where U : class where U : T { }"; CreateCompilation(source).VerifyDiagnostics( // (2,11): error CS0699: 'I<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "I<T>").WithLocation(2, 11), // (8,11): error CS0409: A constraint clause has already been specified for type parameter 'U'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 11)); } [Fact] public void CS0455ERR_BaseConstraintConflict01() { var source = @"class A<T> { } class B : A<int> { } class C<T, U> where T : B, U where U : A<int> { } class D<T, U> where T : A<T> where U : B, T { }"; CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0455: Type parameter 'U' inherits conflicting constraints 'A<T>' and 'B' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "A<T>", "B").WithLocation(8, 12)); } [Fact] public void CS0455ERR_BaseConstraintConflict02() { var source = @"class A<T> { internal virtual void M1<U>() where U : struct, T { } internal virtual void M2<U>() where U : class, T { } } class B1 : A<object> { internal override void M1<U>() { } internal override void M2<U>() { } } class B2 : A<int> { internal override void M1<U>() { } internal override void M2<U>() { } } class B3 : A<string> { internal override void M1<U>() { } internal override void M2<U>() { } } class B4 : A<int?> { internal override void M1<T>() { } internal override void M2<X>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'int' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "int", "class").WithLocation(14, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'string' and 'System.ValueType' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "string", "System.ValueType").WithLocation(18, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'System.ValueType' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "System.ValueType", "struct").WithLocation(18, 31), // (23,31): error CS0455: Type parameter 'T' inherits conflicting constraints 'int?' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "T").WithArguments("T", "int?", "struct").WithLocation(23, 31), // (24,31): error CS0455: Type parameter 'X' inherits conflicting constraints 'int?' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "X").WithArguments("X", "int?", "class").WithLocation(24, 31)); } [Fact] public void CS0456ERR_ConWithValCon() { var source = @"class A<T, U> where T : struct where U : T { } class B<T> where T : struct { void M<U>() where U : T { } struct S<U> where U : T { } }"; CreateCompilation(source).VerifyDiagnostics( // (1,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(1, 12), // (8,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(8, 12), // (9,14): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 14)); } [Fact] public void CS0462ERR_AmbigOverride() { var text = @"class C<T> { public virtual void F(T t) {} public virtual void F(int t) {} } class D : C<int> { public override void F(int t) {} // CS0462 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeOverrideMatches, Line = 3, Column = 24, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigOverride, Line = 9, Column = 25 }); } [Fact] public void CS0466ERR_ExplicitImplParams() { var text = @"interface I { void M1(params int[] a); void M2(int[] a); } class C1 : I { //implicit implementations can add or remove 'params' public virtual void M1(int[] a) { } public virtual void M2(params int[] a) { } } class C2 : I { //explicit implementations can remove but not add 'params' void I.M1(int[] a) { } void I.M2(params int[] a) { } //CS0466 } class C3 : C1 { //overrides can add or remove 'params' public override void M1(params int[] a) { } public override void M2(int[] a) { } } class C4 : C1 { //hiding methods can add or remove 'params' public new void M1(params int[] a) { } public new void M2(int[] a) { } } "; CreateCompilation(text).VerifyDiagnostics( // (18,12): error CS0466: 'C2.I.M2(params int[])' should not have a params parameter since 'I.M2(int[])' does not Diagnostic(ErrorCode.ERR_ExplicitImplParams, "M2").WithArguments("C2.I.M2(params int[])", "I.M2(int[])")); } [Fact] public void CS0470ERR_MethodImplementingAccessor() { var text = @"interface I { int P { get; } } class MyClass : I { public int get_P() { return 0; } // CS0470 public int P2 { get { return 0; } } // OK } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 17 }, //Dev10 doesn't include this new ErrorDescription { Code = (int)ErrorCode.ERR_MethodImplementingAccessor, Line = 8, Column = 16 }); } [Fact] public void CS0500ERR_AbstractHasBody01() { var text = @"namespace NS { abstract public class clx { abstract public void M1() { } internal abstract object M2() { return null; } protected abstract internal void M3(sbyte p) { } public abstract object P { get { return null; } set { } } public abstract event System.Action E { add { } remove { } } public abstract event System.Action X { add => throw null; remove => throw null; } } // class clx } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (5,30): error CS0500: 'clx.M1()' cannot declare a body because it is marked abstract // abstract public void M1() { } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("NS.clx.M1()").WithLocation(5, 30), // (6,34): error CS0500: 'clx.M2()' cannot declare a body because it is marked abstract // internal abstract object M2() { return null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M2").WithArguments("NS.clx.M2()").WithLocation(6, 34), // (7,42): error CS0500: 'clx.M3(sbyte)' cannot declare a body because it is marked abstract // protected abstract internal void M3(sbyte p) { } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("NS.clx.M3(sbyte)").WithLocation(7, 42), // (8,36): error CS0500: 'clx.P.get' cannot declare a body because it is marked abstract // public abstract object P { get { return null; } set { } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("NS.clx.P.get").WithLocation(8, 36), // (8,57): error CS0500: 'clx.P.set' cannot declare a body because it is marked abstract // public abstract object P { get { return null; } set { } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("NS.clx.P.set").WithLocation(8, 57), // (9,47): error CS8712: 'clx.E': abstract event cannot use event accessor syntax // public abstract event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("NS.clx.E").WithLocation(9, 47), // (10,47): error CS8712: 'clx.X': abstract event cannot use event accessor syntax // public abstract event System.Action X { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("NS.clx.X").WithLocation(10, 47)); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0501ERR_ConcreteMissingBody01() { var text = @" namespace NS { public class clx<T> { public void M1(T t); internal V M2<V>(); protected internal void M3(sbyte p); public static int operator+(clx<T> c); } // class clx } "; CreateCompilation(text).VerifyDiagnostics( // (7,21): error CS0501: 'NS.clx<T>.M1(T)' must declare a body because it is not marked abstract, extern, or partial // public void M1(T t); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("NS.clx<T>.M1(T)"), // (8,20): error CS0501: 'NS.clx<T>.M2<V>()' must declare a body because it is not marked abstract, extern, or partial // internal V M2<V>(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M2").WithArguments("NS.clx<T>.M2<V>()"), // (9,33): error CS0501: 'NS.clx<T>.M3(sbyte)' must declare a body because it is not marked abstract, extern, or partial // protected internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M3").WithArguments("NS.clx<T>.M3(sbyte)"), // (10,35): error CS0501: 'NS.clx<T>.operator +(NS.clx<T>)' must declare a body because it is not marked abstract, extern, or partial // public static int operator+(clx<T> c); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("NS.clx<T>.operator +(NS.clx<T>)")); } [Fact] public void CS0501ERR_ConcreteMissingBody02() { var text = @"abstract class C { public int P { get; set { } } public int Q { get { return 0; } set; } public extern object R { get; } // no error protected abstract object S { set; } // no error } "; CreateCompilation(text).VerifyDiagnostics( // (3,20): error CS0501: 'C.P.get' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C.P.get"), // (4,38): error CS0501: 'C.Q.set' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C.Q.set"), // (5,30): warning CS0626: Method, operator, or accessor 'C.R.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.R.get")); } [Fact] public void CS0501ERR_ConcreteMissingBody03() { var source = @"class C { public C(); internal abstract C(C c); extern public C(object o); // no error }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()"), // (4,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,19): warning CS0824: Constructor 'C.C(object)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("C.C(object)")); } [Fact] public void CS0502ERR_AbstractAndSealed01() { var text = @"namespace NS { abstract public class clx { abstract public void M1(); abstract protected void M2<T>(T t); internal abstract object P { get; } abstract public event System.Action E; } // class clx abstract public class cly : clx { abstract sealed override public void M1(); abstract sealed override protected void M2<T>(T t); internal abstract sealed override object P { get; } public abstract sealed override event System.Action E; } // class cly } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 13, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 14, Column = 49 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 15, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 16, Column = 61 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0503ERR_AbstractNotVirtual01() { var source = @"namespace NS { abstract public class clx { abstract virtual internal void M1(); abstract virtual protected void M2<T>(T t); virtual abstract public object P { get; set; } virtual abstract public event System.Action E; } // class clx } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (7,40): error CS0503: The abstract property 'clx.P' cannot be marked virtual // virtual abstract public object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P").WithArguments("property", "NS.clx.P").WithLocation(7, 40), // (6,41): error CS0503: The abstract method 'clx.M2<T>(T)' cannot be marked virtual // abstract virtual protected void M2<T>(T t); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M2").WithArguments("method", "NS.clx.M2<T>(T)").WithLocation(6, 41), // (5,40): error CS0503: The abstract method 'clx.M1()' cannot be marked virtual // abstract virtual internal void M1(); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M1").WithArguments("method", "NS.clx.M1()").WithLocation(5, 40), // (8,53): error CS0503: The abstract event 'clx.E' cannot be marked virtual // virtual abstract public event System.Action E; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "E").WithArguments("event", "NS.clx.E").WithLocation(8, 53)); var nsNamespace = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var clxClass = nsNamespace.GetMembers("clx").Single() as NamedTypeSymbol; Assert.Equal(9, clxClass.GetMembers().Length); } [Fact] public void CS0504ERR_StaticConstant() { var text = @"namespace x { abstract public class clx { static const int i = 0; // CS0504, cannot be both static and const abstract public void f(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstant, Line = 5, Column = 26 }); } [Fact] public void CS0505ERR_CantOverrideNonFunction() { var text = @"public class clx { public int i; } public class cly : clx { public override int i() { return 0; } // CS0505 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonFunction, Line = 8, Column = 24 }); } [Fact] public void CS0506ERR_CantOverrideNonVirtual() { var text = @"namespace MyNameSpace { abstract public class ClassX { public int f() { return 0; } } public class ClassY : ClassX { public override int f() // CS0506 { return 0; } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 13, Column = 29 }); } private const string s_typeWithMixedProperty = @" .class public auto ansi beforefieldinit Base_VirtGet_Set extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_VirtGet_Set::get_Prop() .set instance void Base_VirtGet_Set::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit Base_Get_VirtSet extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname newslot virtual instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_Get_VirtSet::get_Prop() .set instance void Base_Get_VirtSet::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; [WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } "; var comp = CreateCompilationWithILAndMscorlib40(text, s_typeWithMixedProperty); comp.VerifyDiagnostics( // (4,25): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // get { return base.Prop; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "get").WithArguments("Derived1.Prop.get", "Base_Get_VirtSet.Prop.get"), // (16,9): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // set { base.Prop = value; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "set").WithArguments("Derived2.Prop.set", "Base_VirtGet_Set.Prop.set")); } [WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported_NO_ERROR() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } } } "; var comp = CreateCompilationWithILAndMscorlib40(text, s_typeWithMixedProperty); comp.VerifyDiagnostics(); } [WorkItem(539586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539586")] [Fact] public void CS0506ERR_CantOverrideNonVirtual02() { var text = @"public class BaseClass { public virtual int Test() { return 1; } } public class BaseClass2 : BaseClass { public static int Test() // Warning CS0114 { return 1; } } public class MyClass : BaseClass2 { public override int Test() // Error CS0506 { return 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 19, Column = 25 }); } [Fact] public void CS0507ERR_CantChangeAccessOnOverride() { var text = @"abstract public class clx { virtual protected void f() { } } public class cly : clx { public override void f() { } // CS0507 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 8, Column = 26 }); } [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride() { var text = @"abstract public class Clx { public int i = 0; abstract public int F(); } public class Cly : Clx { public override double F() { return 0.0; // CS0508 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 9, Column = 28 }); } [WorkItem(540325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540325")] [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride2() { // When the overriding and overridden methods differ in their generic method // type parameter names, the error message should state what the return type // type should be on the overriding method using its type parameter names, // rather than using the return type of the overridden method. var text = @" class G { internal virtual T GM<T>(T t) { return t; } } class GG : G { internal override void GM<V>(V v) { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS0508: 'GG.GM<V>(V)': return type must be 'V' to match overridden member 'G.GM<T>(T)' // internal override void GM<V>(V v) { } Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GM").WithArguments("GG.GM<V>(V)", "G.GM<T>(T)", "V") ); } [Fact] public void CS0509ERR_CantDeriveFromSealedType01() { var source = @"namespace NS { public struct stx { } public sealed class clx {} public class cly : clx {} public class clz : stx { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0509: 'clz': cannot derive from sealed type 'stx' // public class clz : stx { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "stx").WithArguments("NS.clz", "NS.stx").WithLocation(7, 24), // (6,24): error CS0509: 'cly': cannot derive from sealed type 'clx' // public class cly : clx {} Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "clx").WithArguments("NS.cly", "NS.clx").WithLocation(6, 24)); } [Fact] public void CS0509ERR_CantDeriveFromSealedType02() { var source = @"namespace N1 { enum E { A, B } } namespace N2 { class C : N1.E { } class D : System.Int32 { } class E : int { } } "; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0509: 'E': cannot derive from sealed type 'int' // class E : int { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "int").WithArguments("N2.E", "int").WithLocation(6, 15), // (4,15): error CS0509: 'C': cannot derive from sealed type 'E' // class C : N1.E { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "N1.E").WithArguments("N2.C", "N1.E").WithLocation(4, 15), // (5,15): error CS0509: 'D': cannot derive from sealed type 'int' // class D : System.Int32 { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "System.Int32").WithArguments("N2.D", "int").WithLocation(5, 15)); } [Fact] public void CS0513ERR_AbstractInConcreteClass01() { var source = @"namespace NS { public class clx { abstract public void M1(); internal abstract object M2(); protected abstract internal void M3(sbyte p); public abstract object P { get; set; } } } "; CreateCompilation(source).VerifyDiagnostics( // (8,36): error CS0513: 'clx.P.get' is abstract but it is contained in non-abstract class 'clx' // public abstract object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("NS.clx.P.get", "NS.clx").WithLocation(8, 36), // (8,41): error CS0513: 'clx.P.set' is abstract but it is contained in non-abstract class 'clx' // public abstract object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("NS.clx.P.set", "NS.clx").WithLocation(8, 41), // (6,34): error CS0513: 'clx.M2()' is abstract but it is contained in non-abstract class 'clx' // internal abstract object M2(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M2").WithArguments("NS.clx.M2()", "NS.clx").WithLocation(6, 34), // (7,42): error CS0513: 'clx.M3(sbyte)' is abstract but it is contained in non-abstract class 'clx' // protected abstract internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M3").WithArguments("NS.clx.M3(sbyte)", "NS.clx").WithLocation(7, 42), // (5,30): error CS0513: 'clx.M1()' is abstract but it is contained in non-abstract class 'clx' // abstract public void M1(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M1").WithArguments("NS.clx.M1()", "NS.clx").WithLocation(5, 30)); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" class C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract class 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract class 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract class 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void CS0515ERR_StaticConstructorWithAccessModifiers01() { var text = @"namespace NS { static public class clx { private static clx() { } class C<T, V> { internal static C() { } } } public class clz { public static clz() { } struct S { internal static S() { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 5, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 9, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 15, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 19, Column = 29 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Some - /nostdlib - no mscorlib /// </summary> [Fact] public void CS0518ERR_PredefinedTypeNotFound01() { var text = @"namespace NS { class Test { static int Main() { return 1; } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (3,11): error CS0518: Predefined type 'System.Object' is not defined or imported // class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object"), // (5,16): error CS0518: Predefined type 'System.Int32' is not defined or imported // static int Main() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32"), // (7,20): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32"), // (3,11): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0")); } //[Fact(Skip = "Bad test case")] //public void CS0520ERR_PredefinedTypeBadType() //{ // var text = @""; // var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription { Code = (int)ErrorCode.ERR_PredefinedTypeBadType, Line = 5, Column = 26 } // ); //} [Fact] public void CS0523ERR_StructLayoutCycle01() { var text = @"struct A { A F; // CS0523 } struct B { C F; // CS0523 C G; // no additional error } struct C { B G; // CS0523 } struct D<T> { D<D<object>> F; // CS0523 } struct E { F<E> F; // no error } class F<T> { E G; // no error } struct G { H<G> F; // CS0523 } struct H<T> { G G; // CS0523 } struct J { static J F; // no error } struct K { static L F; // no error } struct L { static K G; // no error } "; CreateCompilation(text).VerifyDiagnostics( // (7,7): error CS0523: Struct member 'B.F' of type 'C' causes a cycle in the struct layout // C F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("B.F", "C").WithLocation(7, 7), // (12,7): error CS0523: Struct member 'C.G' of type 'B' causes a cycle in the struct layout // B G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("C.G", "B").WithLocation(12, 7), // (16,18): error CS0523: Struct member 'D<T>.F' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("D<T>.F", "D<D<object>>").WithLocation(16, 18), // (32,7): error CS0523: Struct member 'H<T>.G' of type 'G' causes a cycle in the struct layout // G G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("H<T>.G", "G").WithLocation(32, 7), // (28,10): error CS0523: Struct member 'G.F' of type 'H<G>' causes a cycle in the struct layout // H<G> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("G.F", "H<G>").WithLocation(28, 10), // (3,7): error CS0523: Struct member 'A.F' of type 'A' causes a cycle in the struct layout // A F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("A.F", "A").WithLocation(3, 7), // (16,18): warning CS0169: The field 'D<T>.F' is never used // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("D<T>.F").WithLocation(16, 18), // (32,7): warning CS0169: The field 'H<T>.G' is never used // G G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("H<T>.G").WithLocation(32, 7), // (12,7): warning CS0169: The field 'C.G' is never used // B G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("C.G").WithLocation(12, 7), // (40,14): warning CS0169: The field 'K.F' is never used // static L F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("K.F").WithLocation(40, 14), // (28,10): warning CS0169: The field 'G.F' is never used // H<G> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("G.F").WithLocation(28, 10), // (8,7): warning CS0169: The field 'B.G' is never used // C G; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(8, 7), // (36,14): warning CS0169: The field 'J.F' is never used // static J F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("J.F").WithLocation(36, 14), // (3,7): warning CS0169: The field 'A.F' is never used // A F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (20,10): warning CS0169: The field 'E.F' is never used // F<E> F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("E.F").WithLocation(20, 10), // (44,14): warning CS0169: The field 'L.G' is never used // static K G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("L.G").WithLocation(44, 14), // (7,7): warning CS0169: The field 'B.F' is never used // C F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F").WithLocation(7, 7), // (24,7): warning CS0169: The field 'F<T>.G' is never used // E G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("F<T>.G").WithLocation(24, 7) ); } [Fact] public void CS0523ERR_StructLayoutCycle02() { var text = @"struct A { A P { get; set; } // CS0523 A Q { get; set; } // no additional error } struct B { C P { get; set; } // CS0523 (no error in Dev10!) } struct C { B Q { get; set; } // CS0523 (no error in Dev10!) } struct D<T> { D<D<object>> P { get; set; } // CS0523 } struct E { F<E> P { get; set; } // no error } class F<T> { E Q { get; set; } // no error } struct G { H<G> P { get; set; } // CS0523 G Q; // no additional error } struct H<T> { G Q; // CS0523 } struct J { static J P { get; set; } // no error } struct K { static L P { get; set; } // no error } struct L { static K Q { get; set; } // no error } struct M { N P { get; set; } // no error } struct N { M Q // no error { get { return new M(); } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,7): error CS0523: Struct member 'A.P' of type 'A' causes a cycle in the struct layout // A P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("A.P", "A"), // (8,7): error CS0523: Struct member 'B.P' of type 'C' causes a cycle in the struct layout // C P { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("B.P", "C"), // (12,7): error CS0523: Struct member 'C.Q' of type 'B' causes a cycle in the struct layout // B Q { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("C.Q", "B"), // (16,18): error CS0523: Struct member 'D<T>.P' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("D<T>.P", "D<D<object>>"), // (28,10): error CS0523: Struct member 'G.P' of type 'H<G>' causes a cycle in the struct layout // H<G> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("G.P", "H<G>"), // (33,7): error CS0523: Struct member 'H<T>.Q' of type 'G' causes a cycle in the struct layout // G Q; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("H<T>.Q", "G"), // (29,7): warning CS0169: The field 'G.Q' is never used // G Q; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("G.Q"), // (33,7): warning CS0169: The field 'H<T>.Q' is never used // G Q; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("H<T>.Q") ); } [WorkItem(540215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540215")] [Fact] public void CS0523ERR_StructLayoutCycle03() { // Static fields should not be considered when // determining struct cycles. (Note: Dev10 does // report these cases as errors though.) var text = @"struct A { B F; // no error } struct B { static A G; // no error } "; CreateCompilation(text).VerifyDiagnostics( // (3,7): warning CS0169: The field 'A.F' is never used // B F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (7,14): warning CS0169: The field 'B.G' is never used // static A G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(7, 14) ); } [WorkItem(541629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541629")] [Fact] public void CS0523ERR_StructLayoutCycle04() { var text = @"struct E { } struct X<T> { public T t; } struct Y { public X<Z> xz; } struct Z { public X<E> xe; public X<Y> xy; } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0523: Struct member 'Y.xz' of type 'X<Z>' causes a cycle in the struct layout // public X<Z> xz; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xz").WithArguments("Y.xz", "X<Z>").WithLocation(9, 17), // (14,17): error CS0523: Struct member 'Z.xy' of type 'X<Y>' causes a cycle in the struct layout // public X<Y> xy; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xy").WithArguments("Z.xy", "X<Y>").WithLocation(14, 17), // (9,17): warning CS0649: Field 'Y.xz' is never assigned to, and will always have its default value // public X<Z> xz; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xz").WithArguments("Y.xz", "").WithLocation(9, 17), // (14,17): warning CS0649: Field 'Z.xy' is never assigned to, and will always have its default value // public X<Y> xy; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xy").WithArguments("Z.xy", "").WithLocation(14, 17), // (5,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", "").WithLocation(5, 14), // (13,17): warning CS0649: Field 'Z.xe' is never assigned to, and will always have its default value // public X<E> xe; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xe").WithArguments("Z.xe", "").WithLocation(13, 17) ); } [WorkItem(541629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541629")] [Fact] public void CS0523ERR_StructLayoutCycle05() { var text = @"struct X<T> { public T t; } struct W<T> { X<W<W<T>>> x; }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0523: Struct member 'W<T>.x' of type 'X<W<W<T>>>' causes a cycle in the struct layout // X<W<W<T>>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("W<T>.x", "X<W<W<T>>>"), // (3,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", ""), // (8,16): warning CS0169: The field 'W<T>.x' is never used // X<W<W<T>>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("W<T>.x") ); } [Fact] public void CS0523ERR_StructLayoutCycle06() { var text = @"struct S1<T, U> { S1<object, object> F; } struct S2<T, U> { S2<U, T> F; } struct S3<T> { T F; } struct S4<T> { S3<S3<T>> F; }"; CreateCompilation(text).VerifyDiagnostics( // (3,24): error CS0523: Struct member 'S1<T, U>.F' of type 'S1<object, object>' causes a cycle in the struct layout // S1<object, object> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S1<T, U>.F", "S1<object, object>").WithLocation(3, 24), // (7,14): error CS0523: Struct member 'S2<T, U>.F' of type 'S2<U, T>' causes a cycle in the struct layout // S2<U, T> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S2<T, U>.F", "S2<U, T>").WithLocation(7, 14), // (7,14): warning CS0169: The field 'S2<T, U>.F' is never used // S2<U, T> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S2<T, U>.F").WithLocation(7, 14), // (11,7): warning CS0169: The field 'S3<T>.F' is never used // T F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S3<T>.F").WithLocation(11, 7), // (15,15): warning CS0169: The field 'S4<T>.F' is never used // S3<S3<T>> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S4<T>.F").WithLocation(15, 15), // (3,24): warning CS0169: The field 'S1<T, U>.F' is never used // S1<object, object> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S1<T, U>.F").WithLocation(3, 24) ); } [WorkItem(872954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872954")] [Fact] public void CS0523ERR_StructLayoutCycle07() { var text = @"struct S0<T> { static S0<T> x; } struct S1<T> { class C { } static S1<C> x; } struct S2<T> { struct S { } static S2<S> x; } struct S3<T> { interface I { } static S3<I> x; } struct S4<T> { delegate void D(); static S4<D> x; } struct S5<T> { enum E { } static S5<E> x; } struct S6<T> { static S6<T[]> x; }"; CreateCompilation(text).VerifyDiagnostics( // (8,18): error CS0523: Struct member 'S1<T>.x' of type 'S1<S1<T>.C>' causes a cycle in the struct layout // static S1<C> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S1<T>.x", "S1<S1<T>.C>").WithLocation(8, 18), // (13,18): error CS0523: Struct member 'S2<T>.x' of type 'S2<S2<T>.S>' causes a cycle in the struct layout // static S2<S> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S2<T>.x", "S2<S2<T>.S>").WithLocation(13, 18), // (18,18): error CS0523: Struct member 'S3<T>.x' of type 'S3<S3<T>.I>' causes a cycle in the struct layout // static S3<I> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S3<T>.x", "S3<S3<T>.I>").WithLocation(18, 18), // (23,18): error CS0523: Struct member 'S4<T>.x' of type 'S4<S4<T>.D>' causes a cycle in the struct layout // static S4<D> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S4<T>.x", "S4<S4<T>.D>").WithLocation(23, 18), // (28,18): error CS0523: Struct member 'S5<T>.x' of type 'S5<S5<T>.E>' causes a cycle in the struct layout // static S5<E> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S5<T>.x", "S5<S5<T>.E>").WithLocation(28, 18), // (32,20): error CS0523: Struct member 'S6<T>.x' of type 'S6<T[]>' causes a cycle in the struct layout // static S6<T[]> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S6<T>.x", "S6<T[]>").WithLocation(32, 20), // (8,18): warning CS0169: The field 'S1<T>.x' is never used // static S1<C> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(8, 18), // (23,18): warning CS0169: The field 'S4<T>.x' is never used // static S4<D> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S4<T>.x").WithLocation(23, 18), // (18,18): warning CS0169: The field 'S3<T>.x' is never used // static S3<I> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S3<T>.x").WithLocation(18, 18), // (3,18): warning CS0169: The field 'S0<T>.x' is never used // static S0<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S0<T>.x").WithLocation(3, 18), // (13,18): warning CS0169: The field 'S2<T>.x' is never used // static S2<S> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S2<T>.x").WithLocation(13, 18), // (28,18): warning CS0169: The field 'S5<T>.x' is never used // static S5<E> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S5<T>.x").WithLocation(28, 18), // (32,20): warning CS0169: The field 'S6<T>.x' is never used // static S6<T[]> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S6<T>.x").WithLocation(32, 20)); } [Fact] public void CS0524ERR_InterfacesCannotContainTypes01() { var text = @"namespace NS { public interface IGoo { interface IBar { } public class cly {} struct S { } private enum E { zero, one } // internal delegate void MyDel(object p); // delegates not in scope yet } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (5,19): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // interface IBar { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "IBar").WithArguments("default interface implementation", "8.0").WithLocation(5, 19), // (6,22): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // public class cly {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "cly").WithArguments("default interface implementation", "8.0").WithLocation(6, 22), // (7,16): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // struct S { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "S").WithArguments("default interface implementation", "8.0").WithLocation(7, 16), // (8,22): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // private enum E { zero, one } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "E").WithArguments("default interface implementation", "8.0").WithLocation(8, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0525ERR_InterfacesCantContainFields01() { var text = @"namespace NS { public interface IGoo { string field1; const ulong field2 = 0; public IGoo field3; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest); comp.VerifyDiagnostics( // (5,16): error CS0525: Interfaces cannot contain instance fields // string field1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "field1").WithLocation(5, 16), // (6,21): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // const ulong field2 = 0; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "field2").WithArguments("default interface implementation", "8.0").WithLocation(6, 21), // (7,21): error CS0525: Interfaces cannot contain instance fields // public IGoo field3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "field3").WithLocation(7, 21) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0526ERR_InterfacesCantContainConstructors01() { var text = @"namespace NS { public interface IGoo { public IGoo() {} internal IGoo(object p1, ref long p2) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 5, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 6, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0527ERR_NonInterfaceInInterfaceList01() { var text = @"namespace NS { class C { } public struct S : object, C { interface IGoo : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 7, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0528ERR_DuplicateInterfaceInBaseList01() { var text = @"namespace NS { public interface IGoo {} public interface IBar { } public class C : IGoo, IGoo { } struct S : IBar, IGoo, IBar { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 5, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 8, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Extra errors - expected /// </summary> [Fact] public void CS0529ERR_CycleInInterfaceInheritance01() { var text = @"namespace NS { class AA : BB { } class BB : CC { } class CC : I3 { } interface I1 : I2 { } interface I2 : I3 { } interface I3 : I1 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 7, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 8, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 9, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0531ERR_InterfaceMemberHasBody01() { var text = @"namespace NS { public interface IGoo { int M1() { return 0; } // CS0531 void M2<T>(T t) { } object P { get { return null; } } } interface IBar<T, V> { V M1(T t) { return default(V); } void M2(ref T t, out V v) { v = default(V); } T P { get { return default(T) } set { } } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (14,39): error CS1002: ; expected // T P { get { return default(T) } set { } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(14, 39) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void AbstractConstructor() { var text = @"namespace NS { public class C { abstract C(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 5, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void StaticFixed() { var text = @"unsafe struct S { public static fixed int x[10]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'static' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("static")); } [WorkItem(895401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895401")] [Fact] public void VolatileFixed() { var text = @"unsafe struct S { public volatile fixed int x[10]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'volatile' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile")); } [WorkItem(895401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895401")] [Fact] public void ReadonlyConst() { var text = @" class C { private readonly int F1 = 123; private const int F2 = 123; private readonly const int F3 = 123; }"; CreateCompilation(text).VerifyDiagnostics( // (6,32): error CS0106: The modifier 'readonly' is not valid for this item // private readonly const int F3 = 123; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F3").WithArguments("readonly"), // (4,26): warning CS0414: The field 'C.F1' is assigned but its value is never used // private readonly int F1 = 123; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F1").WithArguments("C.F1")); } [Fact] public void CS0533ERR_HidingAbstractMethod() { var text = @"namespace x { abstract public class a { abstract public void f(); abstract public void g(); } abstract public class b : a { new abstract public void f(); // CS0533 new abstract internal void g(); //fine since internal public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 34 }); } [WorkItem(539629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539629")] [Fact] public void CS0533ERR_HidingAbstractMethod02() { var text = @" abstract public class B1 { public abstract float goo { set; } } abstract class A1 : B1 { new protected enum goo { } // CS0533 abstract public class B2 { protected abstract void goo(); } abstract class A2 : B2 { new public delegate object goo(); // CS0533 } } namespace NS { abstract public class B3 { public abstract void goo(); } abstract class A3 : B3 { new protected double[] goo; // CS0533 } } "; CreateCompilation(text).VerifyDiagnostics( // (31,32): error CS0533: 'A3.goo' hides inherited abstract member 'B3.goo()' // new protected double[] goo; // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("NS.A3.goo", "NS.B3.goo()").WithLocation(31, 32), // (9,24): error CS0533: 'A1.goo' hides inherited abstract member 'B1.goo' // new protected enum goo { } // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("A1.goo", "B1.goo").WithLocation(9, 24), // (18,36): error CS0533: 'A1.A2.goo' hides inherited abstract member 'A1.B2.goo()' // new public delegate object goo(); // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("A1.A2.goo", "A1.B2.goo()").WithLocation(18, 36), // (31,32): warning CS0649: Field 'A3.goo' is never assigned to, and will always have its default value null // new protected double[] goo; // CS0533 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "goo").WithArguments("NS.A3.goo", "null").WithLocation(31, 32)); } [WorkItem(540464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540464")] [Fact] public void CS0533ERR_HidingAbstractMethod03() { var text = @" public abstract class A { public abstract void f(); public abstract void g(); public abstract void h(); } public abstract class B : A { public override void g() { } } public abstract class C : B { public void h(int a) { } } public abstract class D: C { public new int f; // expected CS0533: 'C.f' hides inherited abstract member 'A.f()' public new int g; // no error public new int h; // no CS0533 here in Dev10, but I'm not sure why not. (VB gives error for this case) } "; CreateCompilation(text).VerifyDiagnostics( // (18,16): error CS0533: 'D.f' hides inherited abstract member 'A.f()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "f").WithArguments("D.f", "A.f()")); } [WorkItem(539629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539629")] [Fact] public void CS0533ERR_HidingAbstractMethod_Combinations() { var text = @" abstract class Base { public abstract void M(); public abstract int P { get; set; } public abstract class C { } } abstract class Derived1 : Base { public new abstract void M(); public new abstract void P(); public new abstract void C(); } abstract class Derived2 : Base { public new abstract int M { get; set; } public new abstract int P { get; set; } public new abstract int C { get; set; } } abstract class Derived3 : Base { public new abstract class M { } public new abstract class P { } public new abstract class C { } } abstract class Derived4 : Base { public new void M() { } public new void P() { } public new void C() { } } abstract class Derived5 : Base { public new int M { get; set; } public new int P { get; set; } public new int C { get; set; } } abstract class Derived6 : Base { public new class M { } public new class P { } public new class C { } } abstract class Derived7 : Base { public new static void M() { } public new static int P { get; set; } public new static class C { } } abstract class Derived8 : Base { public new static int M = 1; public new static class P { }; public new const int C = 2; }"; // CONSIDER: dev10 reports each hidden accessor separately, but that seems silly CreateCompilation(text).VerifyDiagnostics( // (11,30): error CS0533: 'Derived1.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived1.M()", "Base.M()"), // (12,30): error CS0533: 'Derived1.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived1.P()", "Base.P"), // (18,29): error CS0533: 'Derived2.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived2.M", "Base.M()"), // (19,29): error CS0533: 'Derived2.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived2.P", "Base.P"), // (25,31): error CS0533: 'Derived3.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived3.M", "Base.M()"), // (26,31): error CS0533: 'Derived3.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived3.P", "Base.P"), // (32,21): error CS0533: 'Derived4.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived4.M()", "Base.M()"), // (33,21): error CS0533: 'Derived4.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived4.P()", "Base.P"), // (39,20): error CS0533: 'Derived5.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived5.M", "Base.M()"), // (40,20): error CS0533: 'Derived5.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived5.P", "Base.P"), // (46,22): error CS0533: 'Derived6.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived6.M", "Base.M()"), // (47,22): error CS0533: 'Derived6.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived6.P", "Base.P"), // (53,28): error CS0533: 'Derived7.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived7.M()", "Base.M()"), // (54,27): error CS0533: 'Derived7.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived7.P", "Base.P"), // (60,27): error CS0533: 'Derived8.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived8.M", "Base.M()"), // (61,20): error CS0533: 'Derived8.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived8.P", "Base.P")); } [WorkItem(539585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539585")] [Fact] public void CS0534ERR_UnimplementedAbstractMethod() { var text = @" abstract class A<T> { public abstract void M(T t); } abstract class B<T> : A<T> { public abstract void M(string s); } class C : B<string> // CS0534 { public override void M(string s) { } static void Main() { } } public abstract class Base<T> { public abstract void M(T t); public abstract void M(int i); } public class Derived : Base<int> // CS0534 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 13, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }); } [Fact] public void CS0535ERR_UnimplementedInterfaceMember() { var text = @"public interface A { void F(); } public class B : A { } // CS0535 A::F is not implemented "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 18 }); } [Fact] public void CS0537ERR_ObjectCantHaveBases() { var text = @"namespace System { public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateEmptyCompilation(text).VerifyDiagnostics( // (3,20): error CS0246: The type or namespace name 'ICloneable' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ICloneable").WithArguments("ICloneable"), // (3,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } //this should be the same as CS0537ERR_ObjectCantHaveBases, except without the second //error (about ICloneable not being defined) [Fact] public void CS0537ERR_ObjectCantHaveBases_OtherType() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateEmptyCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact] public void CS0537ERR_ObjectCantHaveBases_WithMsCorlib() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; // When System.Object is defined in both source and metadata, dev10 favors // the source version and reports ERR_ObjectCantHaveBases. CreateEmptyCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [Fact] public void CS0538ERR_ExplicitInterfaceImplementationNotInterface() { var text = @"interface MyIFace { } public class MyClass { } class C : MyIFace { void MyClass.G() // CS0538, MyClass not an interface { } int MyClass.P { get { return 1; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 11, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 14, Column = 9 }); } [Fact] public void CS0539ERR_InterfaceMemberNotFound() { var text = @"namespace x { interface I { void m(); } public class clx : I { void I.x() // CS0539 { } void I.m() { } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberNotFound, Line = 10, Column = 14 }); } [Fact] public void CS0540ERR_ClassDoesntImplementInterface() { var text = @"interface I { void m(); } public class Clx { void I.m() { } // CS0540 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ClassDoesntImplementInterface, Line = 8, Column = 10 }); } [Fact] public void CS0541ERR_ExplicitInterfaceImplementationInNonClassOrStruct() { var text = @"namespace x { interface IFace { void F(); int P { set; } } interface IFace2 : IFace { void IFace.F(); // CS0541 int IFace.P { set; } //CS0541 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest).VerifyDiagnostics( // (11,20): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "F").WithArguments("default interface implementation", "8.0").WithLocation(11, 20), // (12,23): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 23), // (12,23): error CS0501: 'IFace2.IFace.P.set' must declare a body because it is not marked abstract, extern, or partial // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("x.IFace2.x.IFace.P.set").WithLocation(12, 23), // (11,20): error CS0501: 'IFace2.IFace.F()' must declare a body because it is not marked abstract, extern, or partial // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "F").WithArguments("x.IFace2.x.IFace.F()").WithLocation(11, 20) ); } [Fact] public void CS0542ERR_MemberNameSameAsType01() { var comp = CreateCompilation( @"namespace NS { class NS { } // no error interface IM { void IM(); } // no error interface IP { object IP { get; } } // no error enum A { A } // no error class B { enum B { } } class C { static void C() { } } class D { object D { get; set; } } class E { int D, E, F; } class F { class F { } } class G { struct G { } } class H { delegate void H(); } class L { class L<T> { } } class K<T> { class K { } } class M<T> { interface M<U> { } } class N { struct N<T, U> { } } struct O { enum O { } } struct P { void P() { } } struct Q { static object Q { get; set; } } struct R { object Q, R; } struct S { class S { } } struct T { interface T { } } struct U { struct U { } } struct V { delegate void V(); } struct W { class W<T> { } } struct X<T> { class X { } } struct Y<T> { interface Y<U> { } } struct Z { struct Z<T, U> { } } } "); comp.VerifyDiagnostics( // (7,20): error CS0542: 'B': member names cannot be the same as their enclosing type // class B { enum B { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "B").WithArguments("B"), // (8,27): error CS0542: 'C': member names cannot be the same as their enclosing type // class C { static void C() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C"), // (9,22): error CS0542: 'D': member names cannot be the same as their enclosing type // class D { object D { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "D").WithArguments("D"), // (10,22): error CS0542: 'E': member names cannot be the same as their enclosing type // class E { int D, E, F; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("E"), // (11,21): error CS0542: 'F': member names cannot be the same as their enclosing type // class F { class F { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "F").WithArguments("F"), // (12,22): error CS0542: 'G': member names cannot be the same as their enclosing type // class G { struct G { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "G").WithArguments("G"), // (13,29): error CS0542: 'H': member names cannot be the same as their enclosing type // class H { delegate void H(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "H").WithArguments("H"), // (14,21): error CS0542: 'L': member names cannot be the same as their enclosing type // class L { class L<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "L").WithArguments("L"), // (15,24): error CS0542: 'K': member names cannot be the same as their enclosing type // class K<T> { class K { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "K").WithArguments("K"), // (16,28): error CS0542: 'M': member names cannot be the same as their enclosing type // class M<T> { interface M<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "M").WithArguments("M"), // (17,22): error CS0542: 'N': member names cannot be the same as their enclosing type // class N { struct N<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "N").WithArguments("N"), // (18,21): error CS0542: 'O': member names cannot be the same as their enclosing type // struct O { enum O { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "O").WithArguments("O"), // (19,21): error CS0542: 'P': member names cannot be the same as their enclosing type // struct P { void P() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "P").WithArguments("P"), // (20,30): error CS0542: 'Q': member names cannot be the same as their enclosing type // struct Q { static object Q { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Q").WithArguments("Q"), // (21,26): error CS0542: 'R': member names cannot be the same as their enclosing type // struct R { object Q, R; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "R").WithArguments("R"), // (22,22): error CS0542: 'S': member names cannot be the same as their enclosing type // struct S { class S { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "S").WithArguments("S"), // (23,26): error CS0542: 'T': member names cannot be the same as their enclosing type // struct T { interface T { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "T").WithArguments("T"), // (24,23): error CS0542: 'U': member names cannot be the same as their enclosing type // struct U { struct U { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "U").WithArguments("U"), // (25,30): error CS0542: 'V': member names cannot be the same as their enclosing type // struct V { delegate void V(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "V").WithArguments("V"), // (26,22): error CS0542: 'W': member names cannot be the same as their enclosing type // struct W { class W<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "W").WithArguments("W"), // (27,25): error CS0542: 'X': member names cannot be the same as their enclosing type // struct X<T> { class X { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "X").WithArguments("X"), // (28,29): error CS0542: 'Y': member names cannot be the same as their enclosing type // struct Y<T> { interface Y<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Y").WithArguments("Y"), // (29,23): error CS0542: 'Z': member names cannot be the same as their enclosing type // struct Z { struct Z<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Z").WithArguments("Z"), // (10,19): warning CS0169: The field 'NS.E.D' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "D").WithArguments("NS.E.D"), // (10,22): warning CS0169: The field 'NS.E.E' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "E").WithArguments("NS.E.E"), // (10,25): warning CS0169: The field 'NS.E.F' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("NS.E.F"), // (21,23): warning CS0169: The field 'NS.R.Q' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("NS.R.Q"), // (21,26): warning CS0169: The field 'NS.R.R' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "R").WithArguments("NS.R.R")); } [Fact] public void CS0542ERR_MemberNameSameAsType02() { // No errors for names from explicit implementations. var source = @"interface IM { void C(); } interface IP { object C { get; } } class C : IM, IP { void IM.C() { } object IP.C { get { return null; } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact(), WorkItem(529156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529156")] public void CS0542ERR_MemberNameSameAsType03() { CreateCompilation( @"class Item { public int this[int i] // CS0542 { get { return 0; } } } ").VerifyDiagnostics(); } [WorkItem(538633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538633")] [Fact] public void CS0542ERR_MemberNameSameAsType04() { var source = @"class get_P { object P { get; set; } // CS0542 } class set_P { object P { set { } } // CS0542 } interface get_Q { object Q { get; } } class C : get_Q { public object Q { get; set; } } interface IR { object R { get; set; } } class get_R : IR { public object R { get; set; } // CS0542 } class set_R : IR { object IR.R { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,16): error CS0542: 'get_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_P").WithLocation(3, 16), // (7,16): error CS0542: 'set_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_P").WithLocation(7, 16), // (23,23): error CS0542: 'get_R': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_R").WithLocation(23, 23)); } [Fact] public void CS0542ERR_MemberNameSameAsType05() { var source = @"namespace N1 { class get_Item { object this[object o] { get { return null; } set { } } // CS0542 } class set_Item { object this[object o] { get { return null; } set { } } // CS0542 } } namespace N2 { interface I { object this[object o] { get; set; } } class get_Item : I { public object this[object o] { get { return null; } set { } } // CS0542 } class set_Item : I { object I.this[object o] { get { return null; } set { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,33): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(5, 33), // (9,54): error CS0542: 'set_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_Item").WithLocation(9, 54), // (20,40): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(20, 40)); } /// <summary> /// Derived class with same name as base class /// property accessor metadata name. /// </summary> [Fact] public void CS0542ERR_MemberNameSameAsType06() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object B1() { } .method public abstract virtual instance void B2(object v) { } .property instance object P() { .get instance object A::B1() .set instance void A::B2(object v) } }"; var reference1 = CompileIL(source1); var source2 = @"class B0 : A { public override object P { get { return null; } set { } } } class B1 : A { public override object P { get { return null; } set { } } } class B2 : A { public override object P { get { return null; } set { } } } class get_P : A { public override object P { get { return null; } set { } } } class set_P : A { public override object P { get { return null; } set { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (72): error CS0542: 'B1': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("B1").WithLocation(7, 32), // (11,53): error CS0542: 'B2': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("B2").WithLocation(11, 53)); } /// <summary> /// Derived class with same name as base class /// event accessor metadata name. /// </summary> [WorkItem(530385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530385")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CS0542ERR_MemberNameSameAsType07() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance void B1(class [mscorlib]System.Action v) { } .method public abstract virtual instance void B2(class [mscorlib]System.Action v) { } .event [mscorlib]System.Action E { .addon instance void A::B1(class [mscorlib]System.Action); .removeon instance void A::B2(class [mscorlib]System.Action); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class B0 : A { public override event Action E; } class B1 : A { public override event Action E; } class B2 : A { public override event Action E; } class add_E : A { public override event Action E; } class remove_E : A { public override event Action E; }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,34): error CS0542: 'B1': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B1").WithLocation(8, 34), // (12,34): error CS0542: 'B2': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B2").WithLocation(12, 34), // (16,34): warning CS0067: The event 'add_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("add_E.E").WithLocation(16, 34), // (12,34): warning CS0067: The event 'B2.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B2.E").WithLocation(12, 34), // (8,34): warning CS0067: The event 'B1.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B1.E").WithLocation(8, 34), // (20,34): warning CS0067: The event 'remove_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("remove_E.E").WithLocation(20, 34), // (4,34): warning CS0067: The event 'B0.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B0.E").WithLocation(4, 34)); } [Fact] public void CS0544ERR_CantOverrideNonProperty() { var text = @"public class a { public int i; } public class b : a { public override int i// CS0544 { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonProperty, Line = 8, Column = 25 }); } [Fact] public void CS0545ERR_NoGetToOverride() { var text = @"public class a { public virtual int i { set { } } } public class b : a { public override int i { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 13, Column = 9 }); } [WorkItem(539321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539321")] [Fact] public void CS0545ERR_NoGetToOverride_Regress() { var text = @"public class A { public virtual int P1 { private get; set; } public virtual int P2 { private get; set; } } public class C : A { public override int P1 { set { } } //fine public sealed override int P2 { set { } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,32): error CS0545: 'C.P2': cannot override because 'A.P2' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.SetMethod.IsVirtual); Assert.False(classAProp1.GetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0546ERR_NoSetToOverride() { var text = @"public class a { public virtual int i { get { return 0; } } } public class b : a { public override int i { set { } // CS0546 error no set } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 15, Column = 9 }); } [WorkItem(539321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539321")] [Fact] public void CS0546ERR_NoSetToOverride_Regress() { var text = @"public class A { public virtual int P1 { get; private set; } public virtual int P2 { get; private set; } } public class C : A { public override int P1 { get { return 0; } } //fine public sealed override int P2 { get { return 0; } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,32): error CS0546: 'C.P2': cannot override because 'A.P2' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.GetMethod.IsVirtual); Assert.False(classAProp1.SetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0547ERR_PropertyCantHaveVoidType() { var text = @"interface I { void P { get; set; } } class C { internal void P { set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 3, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 7, Column = 19 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors() { var text = @"interface I { object P { } } abstract class A { public abstract object P { } } class B { internal object P { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors_Indexer() { var text = @"interface I { object this[int x] { } } abstract class A { public abstract object this[int x] { } } class B { internal object this[int x] { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0549ERR_NewVirtualInSealed01() { var text = @"namespace NS { public sealed class Goo { public virtual void M1() { } internal virtual void M2<X>(X x) { } internal virtual int P1 { get; set; } } sealed class Bar<T> { internal virtual T M1(T t) { return t; } public virtual object P1 { get { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 12, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 13, Column = 36 }); } [Fact] public void CS0549ERR_NewVirtualInSealed02() { var text = @" public sealed class C { public virtual event System.Action E; public virtual event System.Action F { add { } remove { } } public virtual int this[int x] { get { return 0; } set { } } } "; // CONSIDER: it seems a little strange to report it on property accessors but on // events themselves. On the other hand, property accessors can have modifiers, // whereas event accessors cannot. CreateCompilation(text).VerifyDiagnostics( // (4,40): error CS0549: 'C.E' is a new virtual member in sealed class 'C' // public virtual event System.Action E; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "E").WithArguments("C.E", "C"), // (5,40): error CS0549: 'C.F' is a new virtual member in sealed class 'C' // public virtual event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "F").WithArguments("C.F", "C"), // (6,38): error CS0549: 'C.this[int].get' is a new virtual member in sealed class 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "get").WithArguments("C.this[int].get", "C"), // (6,56): error CS0549: 'C.this[int].set' is a new virtual member in sealed class 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "set").WithArguments("C.this[int].set", "C"), // (4,40): warning CS0067: The event 'C.E' is never used // public virtual event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0550ERR_ExplicitPropertyAddingAccessor() { var text = @"namespace x { interface ii { int i { get; } } public class a : ii { int ii.i { get { return 0; } set { } // CS0550 no set in interface } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 19, Column = 13 }); } [Fact] public void CS0551ERR_ExplicitPropertyMissingAccessor() { var text = @"interface ii { int i { get; set; } } public class a : ii { int ii.i { set { } } // CS0551 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 10, Column = 18 }, //CONSIDER: dev10 suppresses this new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 12, Column = 12 }); } [Fact] public void CS0552ERR_ConversionWithInterface() { var text = @" public interface I { } public class C { public static implicit operator I(C c) // CS0552 { return null; } public static implicit operator C(I i) // CS0552 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (77): error CS0552: 'C.implicit operator I(C)': user-defined conversions to or from an interface are not allowed // public static implicit operator I(C c) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I").WithArguments("C.implicit operator I(C)"), // (11,37): error CS0552: 'C.implicit operator C(I)': user-defined conversions to or from an interface are not allowed // public static implicit operator C(I i) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "C").WithArguments("C.implicit operator C(I)")); } [Fact] public void CS0553ERR_ConversionWithBase() { var text = @" public class B { } public class D : B { public static implicit operator B(D d) // CS0553 { return null; } } public struct C { public static implicit operator C?(object c) // CS0553 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,37): error CS0553: 'D.implicit operator B(D)': user-defined conversions to or from a base class are not allowed // public static implicit operator B(D d) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "B").WithArguments("D.implicit operator B(D)"), // (12,37): error CS0553: 'C.implicit operator C?(object)': user-defined conversions to or from a base class are not allowed // public static implicit operator C?(object c) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "C?").WithArguments("C.implicit operator C?(object)")); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public class B { public static implicit operator B(D d) // CS0554 { return null; } } public class D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived class are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0555ERR_IdentityConversion() { var text = @" public class MyClass { public static implicit operator MyClass(MyClass aa) // CS0555 { return new MyClass(); } } public struct S { public static implicit operator S?(S s) { return s; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0555: User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type // public static implicit operator MyClass(MyClass aa) // CS0555 Diagnostic(ErrorCode.ERR_IdentityConversion, "MyClass"), // (11,37): error CS0555: User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type // public static implicit operator S?(S s) { return s; } Diagnostic(ErrorCode.ERR_IdentityConversion, "S?") ); } [Fact] public void CS0556ERR_ConversionNotInvolvingContainedType() { var text = @" public class C { public static implicit operator int(string aa) // CS0556 { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator int(string aa) // CS0556 Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int") ); } [Fact] public void CS0557ERR_DuplicateConversionInClass() { var text = @"namespace x { public class ii { public class iii { public static implicit operator int(iii aa) { return 0; } public static explicit operator int(iii aa) { return 0; } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,45): error CS0557: Duplicate user-defined conversion in type 'x.ii.iii' // public static explicit operator int(iii aa) Diagnostic(ErrorCode.ERR_DuplicateConversionInClass, "int").WithArguments("x.ii.iii") ); } [Fact] public void CS0558ERR_OperatorsMustBeStatic() { var text = @"namespace x { public class ii { public class iii { static implicit operator int(iii aa) // CS0558, add public { return 0; } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (75): error CS0558: User-defined operator 'x.ii.iii.implicit operator int(x.ii.iii)' must be declared static and public // static implicit operator int(iii aa) // CS0558, add public Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("x.ii.iii.implicit operator int(x.ii.iii)") ); } [Fact] public void CS0559ERR_BadIncDecSignature() { var text = @"public class iii { public static iii operator ++(int aa) // CS0559 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static iii operator ++(int aa) // CS0559 Diagnostic(ErrorCode.ERR_BadIncDecSignature, "++")); } [Fact] public void CS0562ERR_BadUnaryOperatorSignature() { var text = @"public class iii { public static iii operator +(int aa) // CS0562 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0562: The parameter of a unary operator must be the containing type // public static iii operator +(int aa) // CS0562 Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "+") ); } [Fact] public void CS0563ERR_BadBinaryOperatorSignature() { var text = @"public class iii { public static int operator +(int aa, int bb) // CS0563 { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0563: One of the parameters of a binary operator must be the containing type // public static int operator +(int aa, int bb) // CS0563 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+") ); } [Fact] public void CS0564ERR_BadShiftOperatorSignature() { var text = @" class C { public static int operator <<(C c1, C c2) // CS0564 { return 0; } public static int operator >>(int c1, int c2) // CS0564 { return 0; } static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator <<(C c1, C c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<"), // (8,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator >>(int c1, int c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>") ); } [Fact] public void CS0567ERR_InterfacesCantContainOperators() { var text = @" interface IA { int operator +(int aa, int bb); // CS0567 } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (4,17): error CS0558: User-defined operator 'IA.operator +(int, int)' must be declared static and public // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("IA.operator +(int, int)").WithLocation(4, 17), // (4,17): error CS0501: 'IA.operator +(int, int)' must declare a body because it is not marked abstract, extern, or partial // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("IA.operator +(int, int)").WithLocation(4, 17), // (4,17): error CS0563: One of the parameters of a binary operator must be the containing type // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(4, 17) ); } [Fact] public void CS0569ERR_CantOverrideBogusMethod() { var source1 = @".class abstract public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_sealed() { } .method public abstract virtual instance void set_sealed(object o) { } } .class abstract public B extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_abstract() { } .method public abstract virtual instance void set_abstract(object o) { } .method public virtual final instance void set_sealed(object o) { ret } .method public virtual final instance object get_sealed() { ldnull ret } // abstract get, sealed set .property instance object P() { .get instance object B::get_abstract() .set instance void B::set_sealed(object) } // sealed get, abstract set .property instance object Q() { .get instance object B::get_sealed() .set instance void B::set_abstract(object) } }"; var reference1 = CompileIL(source1); var source2 = @"class C : B { public override object P { get { return 0; } } public override object Q { set { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (3,28): error CS0569: 'C.P': cannot override 'B.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "P").WithArguments("C.P", "B.P").WithLocation(3, 28), // (4,28): error CS0569: 'C.Q': cannot override 'B.Q' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Q").WithArguments("C.Q", "B.Q").WithLocation(4, 28)); } [Fact] public void CS8036ERR_FieldInitializerInStruct() { var text = @"namespace x { public class clx { public static void Main() { } } public struct cly { clx a = new clx(); // CS8036 int i = 7; // CS8036 const int c = 1; // no error static int s = 2; // no error } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,13): error CS0573: 'cly': cannot have instance property or field initializers in structs // clx a = new clx(); // CS8036 Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "a").WithArguments("x.cly").WithLocation(12, 13), // (13,13): error CS0573: 'cly': cannot have instance property or field initializers in structs // int i = 7; // CS8036 Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "i").WithArguments("x.cly").WithLocation(13, 13), // (12,13): warning CS0169: The field 'cly.a' is never used // clx a = new clx(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("x.cly.a").WithLocation(12, 13), // (13,13): warning CS0169: The field 'cly.i' is never used // int i = 7; // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("x.cly.i").WithLocation(13, 13), // (15,20): warning CS0414: The field 'cly.s' is assigned but its value is never used // static int s = 2; // no error Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("x.cly.s").WithLocation(15, 20) ); } [Fact] public void CS0568ERR_StructsCantContainDefaultConstructor01() { var text = @"namespace x { public struct S1 { public S1() {} struct S2<T> { S2() { } } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)); comp.VerifyDiagnostics( // (5,16): error CS0568: Structs cannot contain explicit parameterless constructors // public S1() {} Diagnostic(ErrorCode.ERR_StructsCantContainDefaultConstructor, "S1").WithLocation(5, 16), // (9,13): error CS0568: Structs cannot contain explicit parameterless constructors // S2() { } Diagnostic(ErrorCode.ERR_StructsCantContainDefaultConstructor, "S2").WithLocation(9, 13) ); } [Fact] public void CS0575ERR_OnlyClassesCanContainDestructors() { var text = @"namespace x { public struct iii { ~iii() // CS0575 { } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OnlyClassesCanContainDestructors, Line = 5, Column = 10 }); } [Fact] public void CS0576ERR_ConflictAliasAndMember01() { var text = @"namespace NS { class B { } } namespace NS { using System; using B = NS.B; class A { public static void Main(String[] args) { B b = null; if (b == b) {} } } struct S { B field; public void M(ref B p) { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,27): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // public void M(ref B p) { } Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,9): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B field; Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (15,13): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B b = null; if (b == b) {} Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,11): warning CS0169: The field 'NS.S.field' is never used // B field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(545463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545463")] [Fact] public void CS0576ERR_ConflictAliasAndMember02() { var source = @" namespace Globals.Errors.ResolveInheritance { using ConflictingAlias = BadUsingNamespace; public class ConflictingAlias { public class Nested { } } namespace BadUsingNamespace { public class UsingNotANamespace { } } class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error class Cls2 : ConflictingAlias::UsingNotANamespace { } // OK class Cls3 : global::Globals.Errors.ResolveInheritance.ConflictingAlias.Nested { } // OK } "; CreateCompilation(source).VerifyDiagnostics( // (12,18): error CS0576: Namespace 'Globals.Errors.ResolveInheritance' contains a definition conflicting with alias 'ConflictingAlias' // class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "ConflictingAlias").WithArguments("ConflictingAlias", "Globals.Errors.ResolveInheritance")); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod() { var text = @"interface I { void m(); } public class MyClass : I { [System.Diagnostics.Conditional(""a"")] // CS0577 void I.m() { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,6): error CS0577: The Conditional attribute is not valid on 'MyClass.I.m()' because it is a constructor, destructor, operator, or explicit interface implementation // [System.Diagnostics.Conditional("a")] // CS0577 Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"System.Diagnostics.Conditional(""a"")").WithArguments("MyClass.I.m()").WithLocation(8, 6)); } [Fact] public void CS0578ERR_ConditionalMustReturnVoid() { var text = @"public class MyClass { [System.Diagnostics.ConditionalAttribute(""a"")] // CS0578 public int TestMethod() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,5): error CS0578: The Conditional attribute is not valid on 'MyClass.TestMethod()' because its return type is not void // [System.Diagnostics.ConditionalAttribute("a")] // CS0578 Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"System.Diagnostics.ConditionalAttribute(""a"")").WithArguments("MyClass.TestMethod()").WithLocation(3, 5)); } [Fact] public void CS0579ERR_DuplicateAttribute() { var text = @"class A : System.Attribute { } class B : System.Attribute { } [A, A] class C { } [B][A][B] class D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 3, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 4, Column = 8 }); } [Fact, WorkItem(528872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528872")] public void CS0582ERR_ConditionalOnInterfaceMethod() { var text = @"using System.Diagnostics; interface MyIFace { [ConditionalAttribute(""DEBUG"")] // CS0582 void zz(); } "; CreateCompilation(text).VerifyDiagnostics( // (4,5): error CS0582: The Conditional attribute is not valid on interface members // [ConditionalAttribute("DEBUG")] // CS0582 Diagnostic(ErrorCode.ERR_ConditionalOnInterfaceMethod, @"ConditionalAttribute(""DEBUG"")").WithLocation(4, 5)); } [Fact] public void CS0590ERR_OperatorCantReturnVoid() { var text = @" public class C { public static void operator +(C c1, C c2) { } public static implicit operator void(C c1) { } public static void operator +(C c) { } public static void operator >>(C c, int x) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c1, C c2) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (5,33): error CS0590: User-defined operators cannot return void // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "void"), // (5,46): error CS1547: Keyword 'void' cannot be used in this context // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (6,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (73): error CS0590: User-defined operators cannot return void // public static void operator >>(C c, int x) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>") ); } [Fact] public void CS0591ERR_InvalidAttributeArgument() { var text = @"using System; [AttributeUsage(0)] // CS0591 class A : Attribute { } [AttributeUsageAttribute(0)] // CS0591 class B : Attribute { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (2,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsage").WithLocation(2, 17), // (4,26): error CS0591: Invalid value for argument to 'AttributeUsageAttribute' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsageAttribute").WithLocation(4, 26)); } [Fact] public void CS0592ERR_AttributeOnBadSymbolType() { var text = @"using System; [AttributeUsage(AttributeTargets.Interface)] public class MyAttribute : Attribute { } [MyAttribute] // Generates CS0592 because MyAttribute is not valid for a class. public class A { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttributeOnBadSymbolType, Line = 8, Column = 2 }); } [Fact()] public void CS0596ERR_ComImportWithoutUuidAttribute() { var text = @"using System.Runtime.InteropServices; namespace x { [ComImport] // CS0596 public class a { } public class b { public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ComImportWithoutUuidAttribute, Line = 5, Column = 6 }); } // CS0599: not used [Fact] public void CS0601ERR_DllImportOnInvalidMethod() { var text = @" using System.Runtime.InteropServices; public class C { [DllImport(""KERNEL32.DLL"")] extern int Goo(); // CS0601 [DllImport(""KERNEL32.DLL"")] static void Bar() { } // CS0601 } "; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (9,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport")); } /// <summary> /// Dev10 doesn't report this error, but emits invalid metadata. /// When the containing type is being loaded TypeLoadException is thrown by the CLR. /// </summary> [Fact] public void CS7042ERR_DllImportOnGenericMethod() { var text = @" using System.Runtime.InteropServices; public class C<T> { class X { [DllImport(""KERNEL32.DLL"")] static extern void Bar(); } } public class C { [DllImport(""KERNEL32.DLL"")] static extern void Bar<T>(); } "; CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport"), // (15,6): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport")); } // CS0609ERR_NameAttributeOnOverride -> BreakChange [Fact] public void CS0610ERR_FieldCantBeRefAny() { var text = @"public class MainClass { System.TypedReference i; // CS0610 public static void Main() { } System.TypedReference Prop { get; set; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference Prop { get; set; } Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,27): warning CS0169: The field 'MainClass.i' is never used // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("MainClass.i") ); } [Fact] public void CS0616ERR_NotAnAttributeClass() { var text = @"[CMyClass] // CS0616 public class CMyClass {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0616ERR_NotAnAttributeClass2() { var text = @"[CMyClass] // CS0616 public class CMyClassAttribute {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0617ERR_BadNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyClass : Attribute { public MyClass(int sName) { Bad = sName; Bad2 = -1; } public readonly int Bad; public int Bad2; } [MyClass(5, Bad = 0)] class Class1 { } // CS0617 [MyClass(5, Bad2 = 0)] class Class2 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgument, Line = 16, Column = 13 }); } [Fact] public void CS0620ERR_IndexerCantHaveVoidType() { var text = @"class MyClass { public static void Main() { MyClass test = new MyClass(); } void this[int intI] // CS0620, return type cannot be void { get { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerCantHaveVoidType, Line = 8, Column = 10 }); } [Fact] public void CS0621ERR_VirtualPrivate01() { var text = @"namespace x { class Goo { private virtual void vf() { } } public class Bar<T> { private virtual void M1(T t) { } virtual V M2<V>(T t); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 9, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("x").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0621ERR_VirtualPrivate02() { var source = @"abstract class A { abstract object P { get; } } class B { private virtual object Q { get; set; } } "; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS0621: 'A.P': virtual or abstract members cannot be private // abstract object P { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("A.P").WithLocation(3, 21), // (7,28): error CS0621: 'B.Q': virtual or abstract members cannot be private // private virtual object Q { get; set; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "Q").WithArguments("B.Q").WithLocation(7, 28)); } [Fact] public void CS0621ERR_VirtualPrivate03() { var text = @"namespace x { abstract class Goo { private virtual void M1<T>(T x) { } private abstract int P { get; set; } } class Bar { private override void M1<T>(T a) { } private override int P { set { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 6, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 11, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 11, Column = 30 }); } [Fact] public void CS0621ERR_VirtualPrivate04() { var text = @" class C { virtual private event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0621: 'C.E': virtual or abstract members cannot be private // virtual private event System.Action E; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E").WithArguments("C.E"), // (4,41): warning CS0067: The event 'C.E' is never used // virtual private event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } // CS0625: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0629ERR_InterfaceImplementedByConditional01() { var text = @"interface MyInterface { void MyMethod(); } public class MyClass : MyInterface { [System.Diagnostics.Conditional(""debug"")] public void MyMethod() // CS0629, remove the Conditional attribute { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceImplementedByConditional, Line = 9, Column = 17 }); } [Fact] public void CS0629ERR_InterfaceImplementedByConditional02() { var source = @" using System.Diagnostics; interface I<T> { void M(T x); } class Base { [Conditional(""debug"")] public void M(int x) {} } class Derived : Base, I<int> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,23): error CS0629: Conditional member 'Base.M(int)' cannot implement interface member 'I<int>.M(int)' in type 'Derived' // class Derived : Base, I<int> Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "I<int>").WithArguments("Base.M(int)", "I<int>.M(int)", "Derived").WithLocation(13, 23)); } [Fact] public void CS0633ERR_BadArgumentToAttribute() { var text = @"#define DEBUG using System.Diagnostics; public class Test { [Conditional(""DEB+UG"")] // CS0633 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'Conditional' attribute must be a valid identifier // [Conditional("DEB+UG")] // CS0633 Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""DEB+UG""").WithArguments("Conditional").WithLocation(5, 18)); } [Fact] public void CS0633ERR_BadArgumentToAttribute_IndexerNameAttribute() { var text = @" using System.Runtime.CompilerServices; class A { [IndexerName(null)] int this[int x] { get { return 0; } set { } } } class B { [IndexerName("""")] int this[int x] { get { return 0; } set { } } } class C { [IndexerName("" "")] int this[int x] { get { return 0; } set { } } } class D { [IndexerName(""1"")] int this[int x] { get { return 0; } set { } } } class E { [IndexerName(""!"")] int this[int x] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, "null").WithArguments("IndexerName"), // (10,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""""").WithArguments("IndexerName"), // (15,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @""" """).WithArguments("IndexerName"), // (20,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""1""").WithArguments("IndexerName"), // (25,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""!""").WithArguments("IndexerName")); } // CS0636: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors // CS0637: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0641ERR_AttributeUsageOnNonAttributeClass() { var text = @"using System; [AttributeUsage(AttributeTargets.Method)] class A { } [System.AttributeUsageAttribute(AttributeTargets.Class)] class B { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (2,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(2, 2), // (4,2): error CS0641: Attribute 'System.AttributeUsageAttribute' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "System.AttributeUsageAttribute").WithArguments("System.AttributeUsageAttribute").WithLocation(4, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyAttribute : Attribute { public MyAttribute() { } public int x; } [MyAttribute(x = 5, x = 6)] // CS0643, error setting x twice class MyClass { } public class MainClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNamedAttributeArgument, Line = 13, Column = 21 }); } [WorkItem(540923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540923")] [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { var text = @"using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(2, 39), // (2,2): error CS76: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(2, 2) ); } [Fact] public void CS0644ERR_DeriveFromEnumOrValueType() { var source = @"using System; namespace N { class C : Enum { } class D : ValueType { } class E : Delegate { } static class F : MulticastDelegate { } static class G : Array { } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0644: 'D' cannot derive from special class 'ValueType' // class D : ValueType { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "ValueType").WithArguments("N.D", "System.ValueType").WithLocation(5, 15), // (6,15): error CS0644: 'E' cannot derive from special class 'Delegate' // class E : Delegate { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Delegate").WithArguments("N.E", "System.Delegate").WithLocation(6, 15), // (4,15): error CS0644: 'C' cannot derive from special class 'Enum' // class C : Enum { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Enum").WithArguments("N.C", "System.Enum").WithLocation(4, 15), // (8,22): error CS0644: 'G' cannot derive from special class 'Array' // static class G : Array { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Array").WithArguments("N.G", "System.Array").WithLocation(8, 22), // (7,22): error CS0644: 'F' cannot derive from special class 'MulticastDelegate' // static class F : MulticastDelegate { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "MulticastDelegate").WithArguments("N.F", "System.MulticastDelegate").WithLocation(7, 22)); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType() { var text = @"[System.Reflection.DefaultMemberAttribute(""x"")] // CS0646 class MyClass { public int this[int index] // an indexer { get { return 0; } } public int x = 0; } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultMemberOnIndexedType, Line = 1, Column = 2 }); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType02() { var text = @" using System.Reflection; interface I { int this[int x] { set; } } [DefaultMember(""X"")] class Program : I { int I.this[int x] { set { } } //doesn't count as an indexer for CS0646 }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType03() { var text = @" using System.Reflection; [DefaultMember(""This is definitely not a valid member name *#&#*"")] class Program { }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0653ERR_AbstractAttributeClass() { var text = @"using System; public abstract class MyAttribute : Attribute { } [My] // CS0653 class MyClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAttributeClass, Line = 7, Column = 2 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType() { var text = @"using System; class MyAttribute : Attribute { public decimal d = 0; public int e = 0; } [My(d = 0)] // CS0655 class C { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgumentType, Line = 9, Column = 5 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1(P = null)] // Dev11 error public class A1 : Attribute { public A1() { } public dynamic P { get; set; } } [A2(P = null)] // Dev11 ok (bug) public class A2 : Attribute { public A2() { } public dynamic[] P { get; set; } } [A3(P = 0)] // Dev11 error (bug) public class A3 : Attribute { public A3() { } public C<dynamic>.D P { get; set; } } [A4(P = null)] // Dev11 ok public class A4 : Attribute { public A4() { } public C<dynamic>.D[] P { get; set; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A1(P = null)] // Dev11 error Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P"), // (13,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A2(P = null)] // Dev11 ok (bug) Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P")); } [Fact] public void CS0656ERR_MissingPredefinedMember() { var text = @"namespace System { public class Object { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } public class Test { public unsafe static int Main() { string str = ""This is my test string""; fixed (char* ptr = str) { if (*(ptr + str.Length) != '\0') return 1; } return 0; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyEmitDiagnostics( // (70,32): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData' // fixed (char* ptr = str) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "str").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData")); } // CS0662: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0663ERR_OverloadRefOut01() { var text = @"namespace NS { public interface IGoo<T> { void M(T t); void M(ref T t); void M(out T t); } internal class CGoo { private struct SGoo { void M<T>(T t) { } void M<T>(ref T t) { } void M<T>(out T t) { } } public int RetInt(byte b, out int i) { return i; } public int RetInt(byte b, ref int j) { return 3; } public int RetInt(byte b, int k) { return 4; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,14): error CS0663: 'IGoo<T>' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' // void M(out T t); Diagnostic(ErrorCode.ERR_OverloadRefKind, "M").WithArguments("NS.IGoo<T>", "method", "out", "ref").WithLocation(7, 14), // (24,20): error CS0663: 'CGoo' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public int RetInt(byte b, ref int j) Diagnostic(ErrorCode.ERR_OverloadRefKind, "RetInt").WithArguments("NS.CGoo", "method", "ref", "out").WithLocation(24, 20), // (16,18): error CS0663: 'CGoo.SGoo' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' // void M<T>(out T t) { } Diagnostic(ErrorCode.ERR_OverloadRefKind, "M").WithArguments("NS.CGoo.SGoo", "method", "out", "ref").WithLocation(16, 18), // (21,20): error CS0269: Use of unassigned out parameter 'i' // return i; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "i").WithArguments("i").WithLocation(21, 20), // (21,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // return i; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return i;").WithArguments("i").WithLocation(21, 13), // (16,18): error CS0177: The out parameter 't' must be assigned to before control leaves the current method // void M<T>(out T t) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("t").WithLocation(16, 18) ); } [Fact] public void CS0666ERR_ProtectedInStruct01() { var text = @"namespace NS { internal struct S1<T, V> { protected T field; protected internal void M(T t, V v) { } protected object P { get { return null; } } // Dev10 no error protected event System.Action E; struct S2 { protected void M1<X>(X p) { } protected internal R M2<X, R>(ref X p, R r) { return r; } protected internal object Q { get; set; } // Dev10 no error protected event System.Action E; } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,21): error CS0666: 'NS.S1<T, V>.field': new protected member declared in struct // protected T field; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("NS.S1<T, V>.field"), // (7,26): error CS0666: 'NS.S1<T, V>.P': new protected member declared in struct // protected object P { get { return null; } } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "P").WithArguments("NS.S1<T, V>.P"), // (8,39): error CS0666: 'NS.S1<T, V>.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.E"), // (6,33): error CS0666: 'NS.S1<T, V>.M(T, V)': new protected member declared in struct // protected internal void M(T t, V v) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M").WithArguments("NS.S1<T, V>.M(T, V)"), // (14,39): error CS0666: 'NS.S1<T, V>.S2.Q': new protected member declared in struct // protected internal object Q { get; set; } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Q").WithArguments("NS.S1<T, V>.S2.Q"), // (15,43): error CS0666: 'NS.S1<T, V>.S2.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.S2.E"), // (12,28): error CS0666: 'NS.S1<T, V>.S2.M1<X>(X)': new protected member declared in struct // protected void M1<X>(X p) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M1").WithArguments("NS.S1<T, V>.S2.M1<X>(X)"), // (13,34): error CS0666: 'NS.S1<T, V>.S2.M2<X, R>(ref X, R)': new protected member declared in struct // protected internal R M2<X, R>(ref X p, R r) { return r; } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M2").WithArguments("NS.S1<T, V>.S2.M2<X, R>(ref X, R)"), // (5,21): warning CS0649: Field 'NS.S1<T, V>.field' is never assigned to, and will always have its default value // protected T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.S1<T, V>.field", ""), // (8,39): warning CS0067: The event 'NS.S1<T, V>.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.E"), // (15,43): warning CS0067: The event 'NS.S1<T, V>.S2.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.S2.E") ); } [Fact] public void CS0666ERR_ProtectedInStruct02() { var text = @"struct S { protected object P { get { return null; } } public int Q { get; protected set; } } struct C<T> { protected internal T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 4, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 45 }); } [Fact] public void CS0666ERR_ProtectedInStruct03() { var text = @" struct S { protected event System.Action E; protected event System.Action F { add { } remove { } } protected int this[int x] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,35): error CS0666: 'S.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("S.E"), // (5,35): error CS0666: 'S.F': new protected member declared in struct // protected event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "F").WithArguments("S.F"), // (6,19): error CS0666: 'S.this[int]': new protected member declared in struct // protected int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "this").WithArguments("S.this[int]"), // (4,35): warning CS0067: The event 'S.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("S.E")); } [Fact] public void CS0668ERR_InconsistentIndexerNames() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { [IndexerName(""IName1"")] public int this[int index] // indexer declaration { get { return index; } set { } } [IndexerName(""IName2"")] public int this[string s] // CS0668, change IName2 to IName1 { get { return int.Parse(s); } set { } } void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InconsistentIndexerNames, Line = 19, Column = 16 }); } [Fact] public void CS0668ERR_InconsistentIndexerNames02() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { public int this[int[] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (12,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (15,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (18,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } /// <summary> /// Same as 02, but with an explicit interface implementation between each pair. /// </summary> [Fact] public void CS0668ERR_InconsistentIndexerNames03() { var text = @" using System.Runtime.CompilerServices; interface I { int this[int[] index] { get; set; } int this[int[,] index] { get; set; } int this[int[,,] index] { get; set; } int this[int[,,,] index] { get; set; } int this[int[,,,,] index] { get; set; } int this[int[,,,,,] index] { get; set; } } class IndexerClass : I { int I.this[int[] index] { get { return 0; } set { } } public int this[int[] index] { get { return 0; } set { } } int I.this[int[,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } int I.this[int[,,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } int I.this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } int I.this[int[,,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } int I.this[int[,,,,,] index] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (23,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (28,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (33,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (38,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact()] public void CS0669ERR_ComImportWithUserCtor() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""00000000-0000-0000-0000-000000000001"")] class TestClass { TestClass() // CS0669, delete constructor to resolve { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS0669: A class with the ComImport attribute cannot have a user-defined constructor // TestClass() // CS0669, delete constructor to resolve Diagnostic(ErrorCode.ERR_ComImportWithUserCtor, "TestClass").WithLocation(5, 5)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType01() { var text = @"namespace NS { public class Goo { void Field2 = 0; public void Field1; public struct SGoo { void Field1; internal void Field2; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,9): error CS0670: Field cannot have void type // void Field2 = 0; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (6,16): error CS0670: Field cannot have void type // public void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (10,13): error CS0670: Field cannot have void type // void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (11,22): error CS0670: Field cannot have void type // internal void Field2; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (5,23): error CS0029: Cannot implicitly convert type 'int' to 'void' // void Field2 = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "void"), // (10,18): warning CS0169: The field 'NS.Goo.SGoo.Field1' is never used // void Field1; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("NS.Goo.SGoo.Field1"), // (11,27): warning CS0649: Field 'NS.Goo.SGoo.Field2' is never assigned to, and will always have its default value // internal void Field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("NS.Goo.SGoo.Field2", "") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0673ERR_SystemVoid01() { var source = @"namespace NS { using System; interface IGoo<T> { Void M(T t); } class Goo { extern Void GetVoid(); struct SGoo : IGoo<Void> { } } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo<Void>").WithArguments("NS.Goo.SGoo", "NS.IGoo<System.Void>.M(System.Void)"), Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "GetVoid").WithArguments("NS.Goo.GetVoid()")); } [Fact] public void CS0674ERR_ExplicitParamArray() { var text = @"using System; public class MyClass { public static void UseParams([ParamArray] int[] list) // CS0674 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitParamArray, Line = 4, Column = 35 }); } [Fact] public void CS0677ERR_VolatileStruct() { var text = @"class TestClass { private volatile long i; // CS0677 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,27): error CS0677: 'TestClass.i': a volatile field cannot be of the type 'long' // private volatile long i; // CS0677 Diagnostic(ErrorCode.ERR_VolatileStruct, "i").WithArguments("TestClass.i", "long"), // (3,27): warning CS0169: The field 'TestClass.i' is never used // private volatile long i; // CS0677 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i") ); } [Fact] public void CS0677ERR_VolatileStruct_TypeParameter() { var text = @" class C1<T> { volatile T f; // CS0677 } class C2<T> where T : class { volatile T f; } class C3<T> where T : struct { volatile T f; // CS0677 } class C4<T> where T : C1<int> { volatile T f; } interface I { } class C5<T> where T : I { volatile T f; // CS0677 } "; CreateCompilation(text).VerifyDiagnostics( // (4,16): error CS0677: 'C1<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C1<T>.f", "T"), // (14,16): error CS0677: 'C3<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C3<T>.f", "T"), // (26,16): error CS0677: 'C5<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C5<T>.f", "T"), // (4,16): warning CS0169: The field 'C1<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C1<T>.f"), // (9,16): warning CS0169: The field 'C2<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C2<T>.f"), // (14,16): warning CS0169: The field 'C3<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C3<T>.f"), // (19,16): warning CS0169: The field 'C4<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C4<T>.f"), // (26,16): warning CS0169: The field 'C5<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C5<T>.f")); } [Fact] public void CS0678ERR_VolatileAndReadonly() { var text = @"class TestClass { private readonly volatile int i; // CS0678 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,35): error CS0678: 'TestClass.i': a field cannot be both volatile and readonly // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.ERR_VolatileAndReadonly, "i").WithArguments("TestClass.i"), // (3,35): warning CS0169: The field 'TestClass.i' is never used // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i")); } [Fact] public void CS0681ERR_AbstractField01() { var text = @"namespace NS { class Goo<T> { public abstract T field; struct SGoo { abstract internal Goo<object> field; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,27): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // public abstract T field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (10,43): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract internal Goo<object> field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (6,27): warning CS0649: Field 'NS.Goo<T>.field' is never assigned to, and will always have its default value // public abstract T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Goo<T>.field", ""), // (10,43): warning CS0649: Field 'NS.Goo<T>.SGoo.field' is never assigned to, and will always have its default value null // abstract internal Goo<object> field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Goo<T>.SGoo.field", "null") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(546447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546447")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS0682ERR_BogusExplicitImpl() { var source1 = @".class interface public abstract I { .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void set_P(object& v) { } .property instance object P() { .get instance object I::get_P() .set instance void I::set_P(object& v) } .method public abstract virtual instance void add_E(class [mscorlib]System.Action v) { } .method public abstract virtual instance void remove_E(class [mscorlib]System.Action& v) { } .event [mscorlib]System.Action E { .addon instance void I::add_E(class [mscorlib]System.Action v); .removeon instance void I::remove_E(class [mscorlib]System.Action& v); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class C1 : I { object I.get_P() { return null; } void I.set_P(ref object v) { } void I.add_E(Action v) { } void I.remove_E(ref Action v) { } } class C2 : I { object I.P { get { return null; } set { } } event Action I.E { add { } remove { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (11,14): error CS0682: 'C2.I.P' cannot implement 'I.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "P").WithArguments("C2.I.P", "I.P").WithLocation(11, 14), // (16,20): error CS0682: 'C2.I.E' cannot implement 'I.E' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "E").WithArguments("C2.I.E", "I.E").WithLocation(16, 20)); } [Fact] public void CS0683ERR_ExplicitMethodImplAccessor() { var text = @"interface IExample { int Test { get; } } class CExample : IExample { int IExample.get_Test() { return 0; } // CS0683 int IExample.Test { get { return 0; } } // correct } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitMethodImplAccessor, Line = 8, Column = 18 }); } [Fact] public void CS0685ERR_ConditionalWithOutParam() { var text = @"namespace NS { using System.Diagnostics; class Test { [Conditional(""DEBUG"")] void Debug(out int i) // CS0685 { i = 1; } [Conditional(""TRACE"")] void Trace(ref string p1, out string p2) // CS0685 { p2 = p1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,10): error CS0685: Conditional member 'NS.Test.Debug(out int)' cannot have an out parameter // [Conditional("DEBUG")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("NS.Test.Debug(out int)").WithLocation(7, 10), // (13,10): error CS0685: Conditional member 'NS.Test.Trace(ref string, out string)' cannot have an out parameter // [Conditional("TRACE")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""TRACE"")").WithArguments("NS.Test.Trace(ref string, out string)").WithLocation(13, 10)); } [Fact] public void CS0686ERR_AccessorImplementingMethod() { var text = @"interface I { int get_P(); } class C : I { public int P { get { return 1; } // CS0686 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AccessorImplementingMethod, Line = 10, Column = 9 }); } [Fact] public void CS0689ERR_DerivingFromATyVar01() { var text = @"namespace NS { interface IGoo<T, V> : V { } internal class A<T> : T // CS0689 { protected struct S : T { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 7, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 9, Column = 30 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0692ERR_DuplicateTypeParameter() { var source = @"class C<T, T> where T : class { void M<U, V, U>() where U : new() { } }"; CreateCompilation(source).VerifyDiagnostics( // (1,12): error CS0692: Duplicate type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(1, 12), // (4,18): error CS0692: Duplicate type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 18)); } [Fact] public void CS0693WRN_TypeParameterSameAsOuterTypeParameter01() { var text = @"namespace NS { interface IGoo<T, V> { void M<T>(); } public struct S<T> { public class Outer<T, V> { class Inner<T> // CS0693 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 5, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 10, Column = 28, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 12, Column = 25, IsWarning = true }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0694ERR_TypeVariableSameAsParent01() { var text = @"namespace NS { interface IGoo { void M<M>(M m); // OK (constraint applies to types but not methods) } class C<C> { public struct S<T, S> { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): error CS0694: Type parameter 'C' has the same name as the containing type, or method // class C<C> Diagnostic(ErrorCode.ERR_TypeVariableSameAsParent, "C").WithArguments("C").WithLocation(8, 13), // (10,28): error CS0694: Type parameter 'S' has the same name as the containing type, or method // public struct S<T, S> Diagnostic(ErrorCode.ERR_TypeVariableSameAsParent, "S").WithArguments("S").WithLocation(10, 28) ); } [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations() { // Note: more detailed unification tests are in TypeUnificationTests.cs var text = @"interface I<T> { } class G1<T1, T2> : I<T1>, I<T2> { } // CS0695 class G2<T1, T2> : I<int>, I<T2> { } // CS0695 class G3<T1, T2> : I<int>, I<short> { } // fine class G4<T1, T2> : I<I<T1>>, I<T1> { } // fine class G5<T1, T2> : I<I<T1>>, I<T2> { } // CS0695 interface I2<T> : I<T> { } class G6<T1, T2> : I<T1>, I2<T2> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 3, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 5, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 11, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 15, Column = 7 }); } [WorkItem(539517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539517")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations2() { var text = @" interface I<T, S> { } class A<T, S> : I<I<T, T>, T>, I<I<T, S>, S> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 4, Column = 7 }); } [WorkItem(539518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539518")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations3() { var text = @" class A<T, S> { class B : A<B, B> { } interface IA { } interface IB : B.IA, B.B.IA { } // fine } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute01() { var text = @"class C<T> : System.Attribute // CS0698 { } "; CreateCompilation(text).VerifyDiagnostics( // (1,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute").WithLocation(1, 14)); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute02() { var text = @"class A : System.Attribute { } class B<T> : A { } class C<T> { class B : A { } }"; CreateCompilation(text).VerifyDiagnostics( // (2,14): error CS0698: A generic type cannot derive from 'A' because it is an attribute class Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "A").WithArguments("A").WithLocation(2, 14), // (5,15): error CS0698: A generic type cannot derive from 'A' because it is an attribute class Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "A").WithArguments("A").WithLocation(5, 15)); } [Fact] public void CS0699ERR_TyVarNotFoundInConstraint() { var source = @"struct S<T> where T : class where U : struct { void M<U, V>() where T : new() where W : class { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0699: 'S<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "S<T>").WithLocation(3, 11), // (6,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'T' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "T").WithArguments("T", "S<T>.M<U, V>()").WithLocation(6, 15), // (7,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'W' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "W").WithArguments("W", "S<T>.M<U, V>()").WithLocation(7, 15)); } [Fact] public void CS0701ERR_BadBoundType() { var source = @"delegate void D(); enum E { } struct S { } sealed class A<T> { } class C { void M1<T>() where T : string { } void M2<T>() where T : D { } void M3<T>() where T : E { } void M4<T>() where T : S { } void M5<T>() where T : A<T> { } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0701: 'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "string").WithArguments("string").WithLocation(7, 28), // (8,28): error CS0701: 'D' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "D").WithArguments("D").WithLocation(8, 28), // (9,28): error CS0701: 'E' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "E").WithArguments("E").WithLocation(9, 28), // (10,28): error CS0701: 'S' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "S").WithArguments("S").WithLocation(10, 28), // (11,28): error CS0701: 'A<T>' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "A<T>").WithArguments("A<T>").WithLocation(11, 28)); } [Fact] public void CS0702ERR_SpecialTypeAsBound() { var source = @"using System; interface IA<T> where T : object { } interface IB<T> where T : System.Object { } interface IC<T, U> where T : ValueType { } interface ID<T> where T : Array { }"; CreateCompilation(source).VerifyDiagnostics( // (2,27): error CS0702: Constraint cannot be special class 'object' // interface IA<T> where T : object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(2, 27), // (3,27): error CS0702: Constraint cannot be special class 'object' // interface IB<T> where T : System.Object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object").WithArguments("object").WithLocation(3, 27), // (4,30): error CS0702: Constraint cannot be special class 'System.ValueType' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "ValueType").WithArguments("System.ValueType").WithLocation(4, 30), // (5,27): error CS0702: Constraint cannot be special class 'System.Array' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "Array").WithArguments("System.Array").WithLocation(5, 27)); } [Fact] public void CS07ERR_BadVisBound01() { var source = @"public class C1 { protected interface I<T> { } internal class A<T> { } public delegate void D<T>() where T : A<T>, I<T>; } public class C2 : C1 { protected struct S<T, U, V> where T : I<A<T>> where U : I<I<U>> where V : A<A<V>> { } internal void M<T, U, V>() where T : A<I<T>> where U : I<I<U>> where V : A<A<V>> { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,43): error CS07: Inconsistent accessibility: constraint type 'C1.A<T>' is less accessible than 'C1.D<T>' // public delegate void D<T>() where T : A<T>, I<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "A<T>").WithArguments("C1.D<T>", "C1.A<T>").WithLocation(5, 43), // (5,49): error CS07: Inconsistent accessibility: constraint type 'C1.I<T>' is less accessible than 'C1.D<T>' // public delegate void D<T>() where T : A<T>, I<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "I<T>").WithArguments("C1.D<T>", "C1.I<T>").WithLocation(5, 49), // (14,19): error CS07: Inconsistent accessibility: constraint type 'C1.A<C1.I<T>>' is less accessible than 'C2.M<T, U, V>()' // where T : A<I<T>> Diagnostic(ErrorCode.ERR_BadVisBound, "A<I<T>>").WithArguments("C2.M<T, U, V>()", "C1.A<C1.I<T>>").WithLocation(14, 19), // (15,19): error CS07: Inconsistent accessibility: constraint type 'C1.I<C1.I<U>>' is less accessible than 'C2.M<T, U, V>()' // where U : I<I<U>> Diagnostic(ErrorCode.ERR_BadVisBound, "I<I<U>>").WithArguments("C2.M<T, U, V>()", "C1.I<C1.I<U>>").WithLocation(15, 19), // (10,19): error CS07: Inconsistent accessibility: constraint type 'C1.I<C1.A<T>>' is less accessible than 'C2.S<T, U, V>' // where T : I<A<T>> Diagnostic(ErrorCode.ERR_BadVisBound, "I<A<T>>").WithArguments("C2.S<T, U, V>", "C1.I<C1.A<T>>").WithLocation(10, 19), // (12,19): error CS07: Inconsistent accessibility: constraint type 'C1.A<C1.A<V>>' is less accessible than 'C2.S<T, U, V>' // where V : A<A<V>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "A<A<V>>").WithArguments("C2.S<T, U, V>", "C1.A<C1.A<V>>").WithLocation(12, 19)); } [Fact] public void CS07ERR_BadVisBound02() { var source = @"internal interface IA<T> { } public interface IB<T, U> { } public class A { public partial class B<T, U> { } public partial class B<T, U> where U : IB<U, IA<T>> { } public partial class B<T, U> where U : IB<U, IA<T>> { } } public partial class C { public partial void M<T>() where T : IA<T>; public partial void M<T>() where T : IA<T> { } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (6,44): error CS07: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' // public partial class B<T, U> where U : IB<U, IA<T>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IB<U, IA<T>>").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(6, 44), // (7,44): error CS07: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' // public partial class B<T, U> where U : IB<U, IA<T>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IB<U, IA<T>>").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(7, 44), // (11,42): error CS07: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' // public partial void M<T>() where T : IA<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "IA<T>").WithArguments("C.M<T>()", "IA<T>").WithLocation(11, 42), // (12,42): error CS07: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' // public partial void M<T>() where T : IA<T> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IA<T>").WithArguments("C.M<T>()", "IA<T>").WithLocation(12, 42)); } [Fact] public void CS0708ERR_InstanceMemberInStaticClass01() { var text = @"namespace NS { public static class Goo { int i; void M() { } internal object P { get; set; } event System.Action E; } static class Bar<T> { T field; T M(T x) { return x; } int Q { get { return 0; } } event System.Action<T> E; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,13): error CS0708: 'NS.Goo.i': cannot declare instance members in a static class // int i; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "i").WithArguments("NS.Goo.i"), // (7,25): error CS0708: 'NS.Goo.P': cannot declare instance members in a static class // internal object P { get; set; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "P").WithArguments("NS.Goo.P"), // (8,29): error CS0708: 'E': cannot declare instance members in a static class // event System.Action E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (6,14): error CS0708: 'M': cannot declare instance members in a static class // void M() { } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (13,11): error CS0708: 'NS.Bar<T>.field': cannot declare instance members in a static class // T field; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "field").WithArguments("NS.Bar<T>.field"), // (15,13): error CS0708: 'NS.Bar<T>.Q': cannot declare instance members in a static class // int Q { get { return 0; } } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "Q").WithArguments("NS.Bar<T>.Q"), // (16,32): error CS0708: 'E': cannot declare instance members in a static class // event System.Action<T> E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (16,32): warning CS0067: The event 'NS.Bar<T>.E' is never used // event System.Action<T> E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Bar<T>.E"), // (8,29): warning CS0067: The event 'NS.Goo.E' is never used // event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Goo.E"), // (14,11): error CS0708: 'M': cannot declare instance members in a static class // T M(T x) { return x; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (5,13): warning CS0169: The field 'NS.Goo.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("NS.Goo.i"), // (13,11): warning CS0169: The field 'NS.Bar<T>.field' is never used // T field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Bar<T>.field")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0709ERR_StaticBaseClass01() { var text = @"namespace NS { public static class Base { } public class Derived : Base { } static class Base1<T, V> { } sealed class Seal<T> : Base1<T, short> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 7, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 15, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0710ERR_ConstructorInStaticClass01() { var text = @"namespace NS { public static class C { public C() {} C(string s) { } static class D<T, V> { internal D() { } internal D(params sbyte[] ary) { } } static C() { } // no error } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 10, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 11, Column = 22 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0711ERR_DestructorInStaticClass() { var text = @"public static class C { ~C() // CS0711 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DestructorInStaticClass, Line = 3, Column = 6 }); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" static class C { static void Main() { C c = new C(); //CS0712 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS07: Cannot declare a variable of static type 'C' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "C").WithArguments("C"), // (6,15): error CS0712: Cannot create an instance of the static class 'C' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new C()").WithArguments("C")); } [Fact] public void CS07ERR_StaticDerivedFromNonObject01() { var source = @"namespace NS { public class Base { } public static class Derived : Base { } class Base1<T, V> { } static class D<V> : Base1<string, V> { } } "; CreateCompilation(source).VerifyDiagnostics( // (75): error CS07: Static class 'Derived' cannot derive from type 'Base'. Static classes must derive from object. // public static class Derived : Base Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Base").WithArguments("NS.Derived", "NS.Base").WithLocation(7, 35), // (15,25): error CS07: Static class 'D<V>' cannot derive from type 'Base1<string, V>'. Static classes must derive from object. // static class D<V> : Base1<string, V> Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Base1<string, V>").WithArguments("NS.D<V>", "NS.Base1<string, V>").WithLocation(15, 25)); } [Fact] public void CS07ERR_StaticDerivedFromNonObject02() { var source = @"delegate void A(); struct B { } static class C : A { } static class D : B { } "; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS07: Static class 'D' cannot derive from type 'B'. Static classes must derive from object. // static class D : B { } Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "B").WithArguments("D", "B").WithLocation(4, 18), // (3,18): error CS07: Static class 'C' cannot derive from type 'A'. Static classes must derive from object. // static class C : A { } Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "A").WithArguments("C", "A").WithLocation(3, 18)); } [Fact] public void CS0714ERR_StaticClassInterfaceImpl01() { var text = @"namespace NS { interface I { } public static class C : I { } interface IGoo<T, V> { } static class D<V> : IGoo<string, V> { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,29): error CS0714: 'NS.C': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "I").WithArguments("NS.C", "NS.I"), // (15,25): error CS0714: 'NS.D<V>': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "IGoo<string, V>").WithArguments("NS.D<V>", "NS.IGoo<string, V>")); } [Fact] public void CS0715ERR_OperatorInStaticClass() { var text = @" public static class C { public static C operator +(C c) // CS0715 { return c; } } "; // Note that Roslyn produces these three errors. The native compiler // produces only the first. We might consider suppressing the additional // "cascading" errors in Roslyn. CreateCompilation(text).VerifyDiagnostics( // (4,30): error CS0715: 'C.operator +(C)': static classes cannot contain user-defined operators // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_OperatorInStaticClass, "+").WithArguments("C.operator +(C)"), // (4,30): error CS0721: 'C': static types cannot be used as parameters // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "+").WithArguments("C"), // (4,19): error CS0722: 'C': static types cannot be used as return types // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "C").WithArguments("C") ); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" static class C { static void M(object o) { M((C)o); M((C)new object()); M((C)null); M((C)1); M((C)""a""); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)o").WithArguments("C"), // (7,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)new object()").WithArguments("C"), // (8,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)null").WithArguments("C"), // (9,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)1").WithArguments("C"), // (10,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)\"a\"").WithArguments("C")); } [Fact] public void CS7023ERR_StaticInIsAsOrIs() { // BREAKING CHANGE: The C# specification states that it is always illegal // BREAKING CHANGE: to use a static type with "is" and "as". The native // BREAKING CHANGE: compiler allows it in some cases; Roslyn does not. var text = @" static class C { static void M(object o) { M(o as C); // legal in native M(new object() as C); // legal in native M(null as C); // legal in native M(1 as C); M(""a"" as C); M(o is C); // legal in native, no warning M(new object() is C); // legal in native, no warning M(null is C); // legal in native, warns M(1 is C); // legal in native, warns M(""a"" is C); // legal in native, warns } } "; var regularComp = CreateCompilation(text); // these diagnostics correspond to those produced by the native compiler. regularComp.VerifyDiagnostics( // (9,11): error CS0039: Cannot convert type 'int' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M(1 as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "1 as C").WithArguments("int", "C").WithLocation(9, 11), // (10,11): error CS0039: Cannot convert type 'string' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M("a" as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"""a"" as C").WithArguments("string", "C").WithLocation(10, 11), // (14,11): warning CS0184: The given expression is never of the provided ('C') type // M(null is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is C").WithArguments("C").WithLocation(14, 11), // (15,11): warning CS0184: The given expression is never of the provided ('C') type // M(1 is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is C").WithArguments("C").WithLocation(15, 11), // (16,11): warning CS0184: The given expression is never of the provided ('C') type // M("a" is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, @"""a"" is C").WithArguments("C").WithLocation(16, 11) ); // in strict mode we also diagnose "is" and "as" operators with a static type. var strictComp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()); strictComp.VerifyDiagnostics( // In the native compiler these three produce no errors. Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "o as C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "new object() as C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "null as C").WithArguments("C"), // In the native compiler these two produce: // error CS0039: Cannot convert type 'int' to 'C' via a reference conversion, boxing conversion, // unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "1 as C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "\"a\" as C").WithArguments("C"), // In the native compiler these two produce no errors: Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "o is C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "new object() is C").WithArguments("C"), // In the native compiler these three produce: // warning CS0184: The given expression is never of the provided ('C') type Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "null is C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "1 is C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "\"a\" is C").WithArguments("C") ); } [Fact] public void CS0717ERR_ConstraintIsStaticClass() { var source = @"static class A { } class B { internal static class C { } } delegate void D<T, U>() where T : A where U : B.C;"; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0717: 'A': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "A").WithArguments("A").WithLocation(4, 15), // (5,15): error CS0717: 'B.C': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "B.C").WithArguments("B.C").WithLocation(5, 15)); } [Fact] public void CS0718ERR_GenericArgIsStaticClass01() { var text = @"interface I<T> { } class C<T> { internal static void M() { } } static class S { static void M<T>() { I<S> i = null; C<S> c = null; C<S>.M(); M<S>(); object o = typeof(I<S>); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,11): error CS0718: 'S': static types cannot be used as type arguments // I<S> i = null; Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(10, 11), // (11,11): error CS0718: 'S': static types cannot be used as type arguments // C<S> c = null; Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(11, 11), // (12,11): error CS0718: 'S': static types cannot be used as type arguments // C<S>.M(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(12, 11), // (13,9): error CS0718: 'S': static types cannot be used as type arguments // M<S>(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "M<S>").WithArguments("S").WithLocation(13, 9), // (14,29): error CS0718: 'S': static types cannot be used as type arguments // object o = typeof(I<S>); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(14, 29), // (10,14): warning CS0219: The variable 'i' is assigned but its value is never used // I<S> i = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(10, 14), // (11,14): warning CS0219: The variable 'c' is assigned but its value is never used // C<S> c = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(11, 14) ); } [Fact] public void CS0719ERR_ArrayOfStaticClass01() { var text = @"namespace NS { public static class C { } static class D<T> { } class Test { public static int Main() { var ca = new C[] { null }; var cd = new D<long>[9]; return 1; } } } "; // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a local because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 14, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 15, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void ERR_VarDeclIsStaticClass02() { // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a field because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var text = @"namespace NS { public static class C { } static class D<T> { } class Test { C[] X; C Y; D<int> Z; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,9): error CS0719: 'NS.C': array elements cannot be of static type // C[] X; Diagnostic(ErrorCode.ERR_ArrayOfStaticClass, "C").WithArguments("NS.C"), // (13,11): error CS07: Cannot declare a variable of static type 'NS.C' // C Y; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Y").WithArguments("NS.C"), // (14,16): error CS07: Cannot declare a variable of static type 'NS.D<int>' // D<int> Z; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Z").WithArguments("NS.D<int>"), // (12,13): warning CS0169: The field 'NS.Test.X' is never used // C[] X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("NS.Test.X"), // (13,11): warning CS0169: The field 'NS.Test.Y' is never used // C Y; Diagnostic(ErrorCode.WRN_UnreferencedField, "Y").WithArguments("NS.Test.Y"), // (14,16): warning CS0169: The field 'NS.Test.Z' is never used // D<int> Z; Diagnostic(ErrorCode.WRN_UnreferencedField, "Z").WithArguments("NS.Test.Z")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0720ERR_IndexerInStaticClass() { var text = @"public static class Test { public int this[int index] // CS0720 { get { return 1; } set {} } static void Main() {} } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerInStaticClass, Line = 3, Column = 16 }); } [Fact] public void CS0721ERR_ParameterIsStaticClass01() { var text = @"namespace NS { public static class C { } public static class D<T> { } interface IGoo<T> { void M(D<T> d); // Dev10 no error? } class Test { public void F(C p) // CS0721 { } struct S { object M<T>(D<T> p1) // CS0721 { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 16, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 22, Column = 20 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0721ERR_ParameterIsStaticClass02() { var source = @"static class S { } class C { S P { set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(4, 11)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass01() { var source = @"namespace NS { public static class C { } public static class D<T> { } interface IGoo<T> { D<T> M(); // Dev10 no error? } class Test { extern public C F(); // CS0722 // { // return default(C); // } struct S { extern D<sbyte> M(); // CS0722 // { // return default(D<sbyte>); // } } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,25): error CS0722: 'NS.C': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("NS.C").WithLocation(16, 25), // (23,29): error CS0722: 'NS.D<sbyte>': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "M").WithArguments("NS.D<sbyte>").WithLocation(23, 29), // (16,25): warning CS0626: Method, operator, or accessor 'NS.Test.F()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "F").WithArguments("NS.Test.F()").WithLocation(16, 25), // (23,29): warning CS0626: Method, operator, or accessor 'NS.Test.S.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.S.M()").WithLocation(23, 29)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass02() { var source = @"static class S { } class C { S P { get { return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(4, 11)); } [WorkItem(530434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530434")] [Fact(Skip = "530434")] public void CS0722ERR_ReturnTypeIsStaticClass03() { var source = @"static class S { } class C { public abstract S F(); public abstract S P { get; } public abstract S Q { set; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,23): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("S").WithLocation(4, 23), // (4,23): error CS0513: 'C.F()' is abstract but it is contained in non-abstract class 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "F").WithArguments("C.F()", "C").WithLocation(4, 23), // (5,27): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract class 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.P.get", "C").WithLocation(5, 27), // (6,27): error CS0513: 'C.Q.set' is abstract but it is contained in non-abstract class 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.Q.set", "C").WithLocation(6, 27), // (5,27): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(5, 27), // (6,27): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(6, 27)); } [WorkItem(546540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546540")] [Fact] public void CS0722ERR_ReturnTypeIsStaticClass04() { var source = @"static class S1 { } static class S2 { } class C { public static S1 operator-(C c) { return null; } public static implicit operator S2(C c) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (5,19): error CS0722: 'S1': static types cannot be used as return types // public static S1 operator-(C c) Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S1").WithArguments("S1"), // (9,37): error CS0722: 'S2': static types cannot be used as return types // public static implicit operator S2(C c) { return null; } Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S2").WithArguments("S2") ); } [Fact] public void CS0729ERR_ForwardedTypeInThisAssembly() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Test))] public class Test { } "; CreateCompilation(csharp).VerifyDiagnostics( // (4,12): error CS0729: Type 'Test' is defined in this assembly, but a type forwarder is specified for it // [assembly: TypeForwardedTo(typeof(Test))] Diagnostic(ErrorCode.ERR_ForwardedTypeInThisAssembly, "TypeForwardedTo(typeof(Test))").WithArguments("Test")); } [Fact] public void CS0730ERR_ForwardedTypeIsNested() { var text1 = @"public class C { public class CC { } } "; var text2 = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(C.CC))]"; var comp1 = CreateCompilation(text1); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilation(text2, new MetadataReference[] { compRef1 }); comp2.VerifyDiagnostics( // (4,12): error CS0730: Cannot forward type 'C.CC' because it is a nested type of 'C' // [assembly: TypeForwardedTo(typeof(C.CC))] Diagnostic(ErrorCode.ERR_ForwardedTypeIsNested, "TypeForwardedTo(typeof(C.CC))").WithArguments("C.CC", "C")); } // See TypeForwarders.Cycle1, etc. //[Fact] //public void CS0731ERR_CycleInTypeForwarder() [Fact] public void CS0735ERR_InvalidFwdType() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(string[]))] [assembly: TypeForwardedTo(typeof(System.Int32*))] "; CreateCompilation(csharp).VerifyDiagnostics( // (4,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(string[]))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(string[]))"), // (5,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(System.Int32*))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(System.Int32*))")); } [Fact] public void CS0736ERR_CloseUnimplementedInterfaceMemberStatic() { var text = @"namespace CS0736 { interface ITest { int testMethod(int x); } class Program : ITest // CS0736 { public static int testMethod(int x) { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 8, Column = 21 }); } [Fact] public void CS0737ERR_CloseUnimplementedInterfaceMemberNotPublic() { var text = @"interface ITest { int Return42(); } struct Struct1 : ITest // CS0737 { int Return42() { return (42); } } public class Test { public static void Main(string[] args) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 6, Column = 18 }); } [Fact] public void CS0738ERR_CloseUnimplementedInterfaceMemberWrongReturnType() { var text = @" interface ITest { int TestMethod(); } public class Test : ITest { public void TestMethod() { } // CS0738 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 7, Column = 21 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_1() { var text = @"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] namespace cs0739 { class Program { static void Main(string[] args) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateTypeForwarder, Line = 2, Column = 12 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_2() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Int32))] [assembly: TypeForwardedTo(typeof(int))] [assembly: TypeForwardedTo(typeof(List<string>))] [assembly: TypeForwardedTo(typeof(List<System.String>))] "; CreateCompilation(csharp).VerifyDiagnostics( // (6,12): error CS0739: 'int' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(int))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(int))").WithArguments("int"), // (9,12): error CS0739: 'System.Collections.Generic.List<string>' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(List<System.String>))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(List<System.String>))").WithArguments("System.Collections.Generic.List<string>")); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_3() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(List<int>))] [assembly: TypeForwardedTo(typeof(List<char>))] [assembly: TypeForwardedTo(typeof(List<>))] "; CreateCompilation(csharp).VerifyDiagnostics(); } [Fact] public void CS0750ERR_PartialMethodInvalidModifier() { var text = @" public class Base { protected virtual void PartG() { } protected void PartH() { } protected virtual void PartI() { } } public partial class C : Base { public partial void PartA(); private partial void PartB(); protected partial void PartC(); internal partial void PartD(); virtual partial void PartE(); abstract partial void PartF(); override partial void PartG(); new partial void PartH(); sealed override partial void PartI(); [System.Runtime.InteropServices.DllImport(""none"")] extern partial void PartJ(); public static int Main() { return 1; } } "; CreateCompilation(text, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (19,25): error CS8793: Partial method 'C.PartA()' must have an implementation part because it has accessibility modifiers. // public partial void PartA(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartA").WithArguments("C.PartA()").WithLocation(19, 25), // (20,26): error CS8793: Partial method 'C.PartB()' must have an implementation part because it has accessibility modifiers. // private partial void PartB(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartB").WithArguments("C.PartB()").WithLocation(20, 26), // (21,28): error CS8793: Partial method 'C.PartC()' must have an implementation part because it has accessibility modifiers. // protected partial void PartC(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartC").WithArguments("C.PartC()").WithLocation(21, 28), // (22,27): error CS8793: Partial method 'C.PartD()' must have an implementation part because it has accessibility modifiers. // internal partial void PartD(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartD").WithArguments("C.PartD()").WithLocation(22, 27), // (29,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.PartJ()' // extern partial void PartJ(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "PartJ").WithArguments("C.PartJ()").WithLocation(29, 25), // (23,26): error CS8796: Partial method 'C.PartE()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void PartE(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartE").WithArguments("C.PartE()").WithLocation(23, 26), // (24,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void PartF(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartF").WithLocation(24, 27), // (25,27): error CS8796: Partial method 'C.PartG()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // override partial void PartG(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartG").WithArguments("C.PartG()").WithLocation(25, 27), // (26,22): error CS8796: Partial method 'C.PartH()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // new partial void PartH(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartH").WithArguments("C.PartH()").WithLocation(26, 22), // (27,34): error CS8796: Partial method 'C.PartI()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartI").WithArguments("C.PartI()").WithLocation(27, 34), // (29,25): error CS8796: Partial method 'C.PartJ()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // extern partial void PartJ(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartJ").WithArguments("C.PartJ()").WithLocation(29, 25), // (25,27): error CS0507: 'C.PartG()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartG()' // override partial void PartG(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartG").WithArguments("C.PartG()", "protected", "Base.PartG()").WithLocation(25, 27), // (27,34): error CS0507: 'C.PartI()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartI()' // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartI").WithArguments("C.PartI()", "protected", "Base.PartI()").WithLocation(27, 34), // (28,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [System.Runtime.InteropServices.DllImport("none")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "System.Runtime.InteropServices.DllImport").WithLocation(28, 6)); } [Fact] public void CS0751ERR_PartialMethodOnlyInPartialClass() { var text = @" public class C { partial void Part(); // CS0751 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyInPartialClass, Line = 5, Column = 18 }); } [Fact] public void CS0752ERR_PartialMethodCannotHaveOutParameters() { var text = @" namespace NS { public partial class C { partial void F(out int x); } } "; CreateCompilation(text, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (7,22): error CS8795: Partial method 'C.F(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void F(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "F").WithArguments("NS.C.F(out int)").WithLocation(7, 22)); } [Fact] public void CS067ERR_ERR_PartialMisplaced() { var text = @" partial class C { partial int f; partial object P { get { return null; } } partial int this[int index] { get { return index; } } partial void M(); } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface', or 'void' // partial int f; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5), // (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface', or 'void' // partial object P { get { return null; } } Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5), // (6,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface', or 'void' // partial int this[int index] Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(6, 5), // (4,17): warning CS0169: The field 'C.f' is never used // partial int f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C.f").WithLocation(4, 17)); } [Fact] public void CS0754ERR_PartialMethodNotExplicit() { var text = @" public interface IF { void Part(); } public partial class C : IF { partial void IF.Part(); //CS0754 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodNotExplicit, Line = 8, Column = 21 }); } [Fact] public void CS0755ERR_PartialMethodExtensionDifference() { var text = @"static partial class C { static partial void M1(this object o); static partial void M1(object o) { } static partial void M2(object o) { } static partial void M2(this object o); }"; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M1").WithLocation(4, 25), // (5,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0756ERR_PartialMethodOnlyOneLatent() { var text = @" public partial class C { partial void Part(); partial void Part(); // CS0756 public static int Main() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0756: A partial method may not have multiple defining declarations // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "Part").WithLocation(5, 18), // (5,18): error CS0111: Type 'C' already defines a member called 'Part' with the same parameter types // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Part").WithArguments("Part", "C").WithLocation(5, 18)); } [Fact] public void CS0757ERR_PartialMethodOnlyOneActual() { var text = @" public partial class C { partial void Part(); partial void Part() { } partial void Part() // CS0757 { } public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyOneActual, Line = 8, Column = 18 }); } [Fact] public void CS0758ERR_PartialMethodParamsDifference() { var text = @"partial class C { partial void M1(params object[] args); partial void M1(object[] args) { } partial void M2(int n, params object[] args) { } partial void M2(int n, object[] args); }"; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M1").WithLocation(4, 18), // (5,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M2").WithLocation(5, 18)); } [Fact] public void CS0759ERR_PartialMethodMustHaveLatent() { var text = @"partial class C { partial void M1() { } partial void M2(); }"; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M1()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M1").WithArguments("C.M1()").WithLocation(3, 18)); } [WorkItem(5427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/5427")] [Fact] public void CS0759ERR_PartialMethodMustHaveLatent_02() { var text = @"using System; static partial class EExtensionMethod { static partial void M(this Array a); } static partial class EExtensionMethod { static partial void M() { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,25): error CS0759: No defining declaration found for implementing declaration of partial method'EExtensionMethod.M()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("EExtensionMethod.M()").WithLocation(9, 25)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints01() { var source = @"interface IA<T> { } interface IB { } partial class C<X> { // Different constraints: partial void A1<T>() where T : struct; partial void A2<T, U>() where T : struct where U : IA<T>; partial void A3<T>() where T : IA<T>; partial void A4<T, U>() where T : struct, IA<T>; // Additional constraints: partial void B1<T>(); partial void B2<T>() where T : X, new(); partial void B3<T, U>() where T : IA<T>; // Missing constraints. partial void C1<T>() where T : class; partial void C2<T>() where T : class, new(); partial void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. partial void D1<T>() where T : IA<T>, IB { } partial void D2<T, U, V>() where V : T, U, X { } // Different constraint clauses. partial void E1<T, U>() where U : T { } // Additional constraint clause. partial void F1<T, U>() where T : class { } // Missing constraint clause. partial void G1<T, U>() where T : class where U : T { } // Same constraint clauses, different order. partial void H1<T, U>() where T : class where U : T { } partial void H2<T, U>() where T : class where U : T { } partial void H3<T, U, V>() where V : class where U : IB where T : IA<V> { } // Different type parameter names. partial void K1<T, U>() where T : class where U : IA<T> { } partial void K2<T, U>() where T : class where U : T, IA<U> { } } partial class C<X> { // Different constraints: partial void A1<T>() where T : class { } partial void A2<T, U>() where T : struct where U : IB { } partial void A3<T>() where T : IA<IA<T>> { } partial void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: partial void B1<T>() where T : new() { } partial void B2<T>() where T : class, X, new() { } partial void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. partial void C1<T>() { } partial void C2<T>() where T : class { } partial void C3<T, U>() where U : IA<T> { } // Same constraints, different order. partial void D1<T>() where T : IB, IA<T>; partial void D2<T, U, V>() where V : U, X, T; // Different constraint clauses. partial void E1<T, U>() where T : class; // Additional constraint clause. partial void F1<T, U>() where T : class where U : T; // Missing constraint clause. partial void G1<T, U>() where T : class; // Same constraint clauses, different order. partial void H1<T, U>() where U : T where T : class; partial void H2<T, U>() where U : class where T : U; partial void H3<T, U, V>() where T : IA<V> where U : IB where V : class; // Different type parameter names. partial void K1<U, T>() where T : class where U : IA<T>; partial void K2<T1, T2>() where T1 : class where T2 : T1, IA<T2>; }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilation(source).VerifyDiagnostics( // (39,18): error CS0761: Partial method declarations of 'C<X>.A2<T, U>()' have inconsistent constraints for type parameter 'U' // partial void A2<T, U>() where T : struct where U : IB { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A2").WithArguments("C<X>.A2<T, U>()", "U").WithLocation(39, 18), // (40,18): error CS0761: Partial method declarations of 'C<X>.A3<T>()' have inconsistent constraints for type parameter 'T' // partial void A3<T>() where T : IA<IA<T>> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A3").WithArguments("C<X>.A3<T>()", "T").WithLocation(40, 18), // (41,18): error CS0761: Partial method declarations of 'C<X>.A4<T, U>()' have inconsistent constraints for type parameter 'T' // partial void A4<T, U>() where T : struct, IA<U> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A4").WithArguments("C<X>.A4<T, U>()", "T").WithLocation(41, 18), // (43,18): error CS0761: Partial method declarations of 'C<X>.B1<T>()' have inconsistent constraints for type parameter 'T' // partial void B1<T>() where T : new() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B1").WithArguments("C<X>.B1<T>()", "T").WithLocation(43, 18), // (44,18): error CS0761: Partial method declarations of 'C<X>.B2<T>()' have inconsistent constraints for type parameter 'T' // partial void B2<T>() where T : class, X, new() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B2").WithArguments("C<X>.B2<T>()", "T").WithLocation(44, 18), // (45,18): error CS0761: Partial method declarations of 'C<X>.B3<T, U>()' have inconsistent constraints for type parameter 'T' // partial void B3<T, U>() where T : IB, IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B3").WithArguments("C<X>.B3<T, U>()", "T").WithLocation(45, 18), // (47,18): error CS0761: Partial method declarations of 'C<X>.C1<T>()' have inconsistent constraints for type parameter 'T' // partial void C1<T>() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C1").WithArguments("C<X>.C1<T>()", "T").WithLocation(47, 18), // (48,18): error CS0761: Partial method declarations of 'C<X>.C2<T>()' have inconsistent constraints for type parameter 'T' // partial void C2<T>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C2").WithArguments("C<X>.C2<T>()", "T").WithLocation(48, 18), // (49,18): error CS0761: Partial method declarations of 'C<X>.C3<T, U>()' have inconsistent constraints for type parameter 'U' // partial void C3<T, U>() where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C3").WithArguments("C<X>.C3<T, U>()", "U").WithLocation(49, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent constraints for type parameter 'T' // partial void E1<T, U>() where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()", "T").WithLocation(22, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void E1<T, U>() where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()", "U").WithLocation(22, 18), // (24,18): error CS0761: Partial method declarations of 'C<X>.F1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void F1<T, U>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "F1").WithArguments("C<X>.F1<T, U>()", "U").WithLocation(24, 18), // (26,18): error CS0761: Partial method declarations of 'C<X>.G1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void G1<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "G1").WithArguments("C<X>.G1<T, U>()", "U").WithLocation(26, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent constraints for type parameter 'T' // partial void H2<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()", "T").WithLocation(29, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent constraints for type parameter 'U' // partial void H2<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()", "U").WithLocation(29, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent constraints for type parameter 'T' // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()", "T").WithLocation(32, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()", "U").WithLocation(32, 18), // (38,18): error CS0761: Partial method declarations of 'C<X>.A1<T>()' have inconsistent constraints for type parameter 'T' // partial void A1<T>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A1").WithArguments("C<X>.A1<T>()", "T").WithLocation(38, 18)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints02() { var source = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class C { partial void M1<T>() where T : A, NIBA; partial void M2<T>() where T : NA, IB<IA>; partial void M3<T, U>() where U : NIBAC; partial void M4<T, U>() where T : U, NIA; } partial class C { partial void M1<T>() where T : N.A, IB<IA> { } partial void M2<T>() where T : A, NIBA { } partial void M3<T, U>() where U : N.IB<A.IC> { } partial void M4<T, U>() where T : NIA { } } }"; CreateCompilation(source).VerifyDiagnostics( // (25,22): error CS0761: Partial method declarations of 'C.M4<T, U>()' have inconsistent constraints for type parameter 'T' // partial void M4<T, U>() where T : NIA { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "M4").WithArguments("N.C.M4<T, U>()", "T").WithLocation(25, 22)); } [Fact] public void CS07ERR_PartialMethodStaticDifference() { var text = @"partial class C { static partial void M1(); partial void M1() { } static partial void M2() { } partial void M2(); }"; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS07: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M1").WithLocation(4, 18), // (5,25): error CS07: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0764ERR_PartialMethodUnsafeDifference() { var text = @"partial class C { unsafe partial void M1(); partial void M1() { } unsafe partial void M2() { } partial void M2(); }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,18): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M1").WithLocation(4, 18), // (5,25): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0766ERR_PartialMethodMustReturnVoid() { var text = @" public partial class C { partial int Part(); partial int Part() { return 1; } public static int Main() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): error CS8794: Partial method 'C.Part()' must have accessibility modifiers because it has a non-void return type. // partial int Part(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "Part").WithArguments("C.Part()").WithLocation(5, 17), // (6,17): error CS8794: Partial method 'C.Part()' must have accessibility modifiers because it has a non-void return type. // partial int Part() Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "Part").WithArguments("C.Part()").WithLocation(6, 17)); } [Fact] public void CS0767ERR_ExplicitImplCollisionOnRefOut() { var text = @"interface IFace<T> { void Goo(ref T x); void Goo(out int x); } class A : IFace<int> { void IFace<int>.Goo(ref int x) { } void IFace<int>.Goo(out int x) { x = 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 }, //error for IFace<int, int>.Goo(ref int) new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 } //error for IFace<int, int>.Goo(out int) ); } [Fact] public void CS0825ERR_TypeVarNotFound01() { var text = @"namespace NS { class Test { static var myStaticField; extern private var M(); void MM(ref var v) { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,24): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // extern private var M(); Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (7,21): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // void MM(ref var v) { } Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (5,16): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // static var myStaticField; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (6,28): warning CS0626: Method, operator, or accessor 'NS.Test.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern private var M(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.M()"), // (5,20): warning CS0169: The field 'NS.Test.myStaticField' is never used // static var myStaticField; Diagnostic(ErrorCode.WRN_UnreferencedField, "myStaticField").WithArguments("NS.Test.myStaticField") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(22512, "https://github.com/dotnet/roslyn/issues/22512")] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public int Num // CS0625 { get; set; } static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,20): error CS0625: 'Str.Num': instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int Num // CS0625 Diagnostic(ErrorCode.ERR_MissingStructOffset, "Num").WithArguments("TestNamespace.Str.Num").WithLocation(9, 20) ); } [Fact] [WorkItem(1032724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032724")] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty_Bug1032724() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public static int Num { get; set; } static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0851ERR_OverloadRefOutCtor() { var text = @"namespace TestNamespace { class MyClass { public MyClass(ref int num) { } public MyClass(out int num) { num = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0663: 'MyClass' cannot define an overloaded constructor that differs only on parameter modifiers 'out' and 'ref' // public MyClass(out int num) Diagnostic(ErrorCode.ERR_OverloadRefKind, "MyClass").WithArguments("TestNamespace.MyClass", "constructor", "out", "ref").WithLocation(8, 17)); } [Fact] public void CS1014ERR_GetOrSetExpected() { var source = @"partial class C { public object P { partial get; set; } object Q { get { return 0; } add { } } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS1014: A get, set or init accessor expected // public object P { partial get; set; } Diagnostic(ErrorCode.ERR_GetOrSetExpected, "partial").WithLocation(3, 23), // (4,34): error CS1014: A get, set or init accessor expected // object Q { get { return 0; } add { } } Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 34)); } [Fact] public void CS1057ERR_ProtectedInStatic01() { var text = @"namespace NS { public static class B { protected static object field = null; internal protected static void M() {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 5, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 6, Column = 40 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CanNotDeclareProtectedPropertyInStaticClass() { const string text = @" static class B { protected static int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }); } [Fact] public void CanNotDeclareProtectedInternalPropertyInStaticClass() { const string text = @" static class B { internal static protected int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 37 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 42 }); } [Fact] public void CanNotDeclarePropertyWithProtectedInternalAccessorInStaticClass() { const string text = @" static class B { public static int X { get; protected internal set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic }); } /// <summary> /// variance /// </summary> [Fact] public void CS1067ERR_PartialWrongTypeParamsVariance01() { var text = @"namespace NS { //combinations partial interface I1<in T> { } partial interface I1<out T> { } partial interface I2<in T> { } partial interface I2<T> { } partial interface I3<T> { } partial interface I3<out T> { } //no duplicate errors partial interface I4<T, U> { } partial interface I4<out T, out U> { } //prefer over CS0264 partial interface I5<S> { } partial interface I5<out T> { } //no error after CS0264 partial interface I6<R, in T> { } partial interface I6<S, out T> { } //no error since arities don't match partial interface I7<T> { } partial interface I7<in T, U> { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,23): error CS1067: Partial declarations of 'NS.I1<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I1").WithArguments("NS.I1<T>"), // (7,23): error CS1067: Partial declarations of 'NS.I2<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I2").WithArguments("NS.I2<T>"), // (10,23): error CS1067: Partial declarations of 'NS.I3<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I3").WithArguments("NS.I3<T>"), // (14,23): error CS1067: Partial declarations of 'NS.I4<T, U>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I4").WithArguments("NS.I4<T, U>"), // (18,23): error CS1067: Partial declarations of 'NS.I5<S>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I5").WithArguments("NS.I5<S>"), // (22,23): error CS0264: Partial declarations of 'NS.I6<R, T>' must have the same type parameter names in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParams, "I6").WithArguments("NS.I6<R, T>")); } [Fact] public void CS1100ERR_BadThisParam() { var text = @"static class Test { static void ExtMethod(int i, this Goo1 c) // CS1100 { } } class Goo1 { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (3,34): error CS1100: Method 'ExtMethod' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("ExtMethod").WithLocation(3, 34)); } [Fact] public void CS1103ERR_BadTypeforThis01() { // Note that the dev11 compiler does not report error CS0721, that C cannot be used as a parameter type. // This appears to be a shortcoming of the dev11 compiler; there is no good reason to not report the error. var compilation = CreateCompilation( @"static class C { static void M1(this Unknown u) { } static void M2(this C c) { } static void M3(this dynamic d) { } static void M4(this dynamic[] d) { } }"); compilation.VerifyDiagnostics( // (3,25): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown"), // (4,17): error CS0721: 'C': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M2").WithArguments("C"), // (5,25): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic")); } [Fact] public void CS1103ERR_BadTypeforThis02() { CreateCompilation( @"public static class Extensions { public unsafe static char* Test(this char* charP) { return charP; } // CS1103 } ", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadTypeforThis, "char*").WithArguments("char*").WithLocation(3, 42)); } [Fact] public void CS1105ERR_BadExtensionMeth() { var text = @"public class Extensions { public void Test<T>(this System.String s) { } //CS1105 } "; var reference = SystemCoreRef; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { reference }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadExtensionAgg, Line = 1, Column = 14 }); } [Fact] public void CS1106ERR_BadExtensionAgg01() { var compilation = CreateCompilation( @"class A { static void M(this object o) { } } class B { static void M<T>(this object o) { } } static class C<T> { static void M(this object o) { } } static class D<T> { static void M<U>(this object o) { } } struct S { static void M(this object o) { } } struct T { static void M<U>(this object o) { } } struct U<T> { static void M(this object o) { } }"); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExtensionAgg, "A").WithLocation(1, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(5, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(9, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "D").WithLocation(13, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "S").WithLocation(17, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "T").WithLocation(21, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "U").WithLocation(25, 8)); } [WorkItem(528256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528256")] [Fact()] public void CS1106ERR_BadExtensionAgg02() { CreateCompilation( @"interface I { static void M(this object o); }", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (3,17): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static void M(this object o); Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "M").WithArguments("static", "7.0", "8.0").WithLocation(3, 17), // (1,11): error CS1106: Extension method must be defined in a non-generic static class // interface I Diagnostic(ErrorCode.ERR_BadExtensionAgg, "I").WithLocation(1, 11), // (3,17): error CS0501: 'I.M(object)' must declare a body because it is not marked abstract, extern, or partial // static void M(this object o); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("I.M(object)").WithLocation(3, 17) ); } [Fact] public void CS1109ERR_ExtensionMethodsDecl() { var compilation = CreateCompilation( @"class A { static class C { static void M(this object o) { } } } static class B { static class C { static void M(this object o) { } } } struct S { static class C { static void M(this object o) { } } }"); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(5, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(12, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(19, 21)); } [Fact] public void CS1110ERR_ExtensionAttrNotFound() { //Extension method cannot be declared without a reference to System.Core.dll var source = @"static class A { public static void M1(this object o) { } public static void M2(this string s, this object o) { } public static void M3(this dynamic d) { } } class B { public static void M4(this object o) { } }"; var compilation = CreateEmptyCompilation(source, new[] { MscorlibRef }); compilation.VerifyDiagnostics( // (3,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(3, 27), // (4,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(4, 27), // (4,42): error CS1100: Method 'M2' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M2").WithLocation(4, 42), // (5,32): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(5, 32), // (5,32): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(5, 32), // (7,7): error CS1106: Extension methods must be defined in a non-generic static class Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(7, 7)); } [Fact] public void CS1112ERR_ExplicitExtension() { var source = @"using System.Runtime.CompilerServices; [System.Runtime.CompilerServices.ExtensionAttribute] static class A { static void M(object o) { } } static class B { [Extension] static void M() { } [ExtensionAttribute] static void M(this object o) { } [Extension] static object P { [Extension] get { return null; } } [Extension(0)] static object F; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [System.Runtime.CompilerServices.ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "System.Runtime.CompilerServices.ExtensionAttribute"), // (9,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (11,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "ExtensionAttribute"), // (13,6): error CS0592: Attribute 'Extension' is not valid on this declaration type. It is only valid on 'assembly, class, method' declarations. // [Extension] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Extension").WithArguments("Extension", "assembly, class, method"), // (16,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (19,6): error CS1729: 'System.Runtime.CompilerServices.ExtensionAttribute' does not contain a constructor that takes 1 arguments // [Extension(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Extension(0)").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "1"), // (20,19): warning CS0169: The field 'B.F' is never used // static object F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F")); } [Fact] public void CS1509ERR_ImportNonAssembly() { //CSC /TARGET:library /reference:class1.netmodule text.CS var text = @"class Test { public static int Main() { return 1; } }"; var ref1 = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "NetModule.mod"); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // error CS1509: The referenced file 'NetModule.mod' is not an assembly Diagnostic(ErrorCode.ERR_ImportNonAssembly).WithArguments(@"NetModule.mod")); } [Fact] public void CS1527ERR_NoNamespacePrivate1() { var text = @"private class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 15 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate2() { var text = @"protected class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 17 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate3() { var text = @"protected internal class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 26 } //pos = the class name ); } [Fact] public void CS1537ERR_DuplicateAlias1() { var text = @"using A = System; using A = System; namespace NS { using O = System.Object; using O = System.Object; }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,7): error CS1537: The using alias 'A' appeared previously in this namespace // using A = System; Diagnostic(ErrorCode.ERR_DuplicateAlias, "A").WithArguments("A"), // (7,11): error CS1537: The using alias 'O' appeared previously in this namespace // using O = System.Object; Diagnostic(ErrorCode.ERR_DuplicateAlias, "O").WithArguments("O"), // (1,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (2,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (6,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;"), // (7,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [WorkItem(537684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537684")] [Fact] public void CS1537ERR_DuplicateAlias2() { var text = @"namespace namespace1 { class A { } } namespace namespace2 { class B { } } namespace NS { using ns = namespace1; using ns = namespace2; using System; class C : ns.A { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,11): error CS1537: The using alias 'ns' appeared previously in this namespace // using ns = namespace2; Diagnostic(ErrorCode.ERR_DuplicateAlias, "ns").WithArguments("ns"), // (14,5): info CS8019: Unnecessary using directive. // using ns = namespace2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ns = namespace2;"), // (15,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("C").Single() as NamedTypeSymbol; var b = type1.BaseType(); } [Fact] public void CS1537ERR_DuplicateAlias3() { var text = @"using X = System; using X = ABC.X<int>;"; CreateCompilation(text).VerifyDiagnostics( // (2,7): error CS1537: The using alias 'X' appeared previously in this namespace // using X = ABC.X<int>; Diagnostic(ErrorCode.ERR_DuplicateAlias, "X").WithArguments("X"), // (1,1): info CS8019: Unnecessary using directive. // using X = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = System;"), // (2,1): info CS8019: Unnecessary using directive. // using X = ABC.X<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = ABC.X<int>;")); } [WorkItem(539125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539125")] [Fact] public void CS1542ERR_AddModuleAssembly() { //CSC /addmodule:cs1542.dll /TARGET:library text1.cs var text = @"public class Goo : IGoo { public void M0() { } }"; var ref1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.NoMsCorLibRef).GetReference(display: "NoMsCorLibRef.mod"); CreateCompilation(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1542: 'NoMsCorLibRef.mod' cannot be added to this assembly because it already is an assembly Diagnostic(ErrorCode.ERR_AddModuleAssembly).WithArguments(@"NoMsCorLibRef.mod"), // (1,20): error CS0246: The type or namespace name 'IGoo' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IGoo").WithArguments("IGoo")); } [Fact, WorkItem(544910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544910")] public void CS1599ERR_MethodReturnCantBeRefAny() { var text = @" using System; interface I { ArgIterator M(); // 1599 } class C { public delegate TypedReference Test1(); // 1599 public RuntimeArgumentHandle Test2() // 1599 { return default(RuntimeArgumentHandle); } // The native compiler does not catch this one; Roslyn does. public static ArgIterator operator +(C c1, C c2) // 1599 { return default(ArgIterator); } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (5,5): error CS1599: Method or delegate cannot return type 'System.ArgIterator' // ArgIterator M(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (11,12): error CS1599: Method or delegate cannot return type 'System.RuntimeArgumentHandle' // public RuntimeArgumentHandle Test2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle"), // (17,19): error CS1599: Method or delegate cannot return type 'System.ArgIterator' // public static ArgIterator operator +(C c1, C c2) // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (9,21): error CS1599: Method or delegate cannot return type 'System.TypedReference' // public delegate TypedReference Test1(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference") ); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionReturnCantBeRefAny() { var text = @" class C { public void Goo() { System.TypedReference local1() // 1599 { return default; } local1(); System.RuntimeArgumentHandle local2() // 1599 { return default; } local2(); System.ArgIterator local3() // 1599 { return default; } local3(); } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (6,9): error CS1599: Method or delegate cannot return type 'TypedReference' // System.TypedReference local1() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(6, 9), // (12,9): error CS1599: Method or delegate cannot return type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle local2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(12, 9), // (18,9): error CS1599: Method or delegate cannot return type 'ArgIterator' // System.ArgIterator local3() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(18, 9)); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionReturnCanBeSpan() { var text = @" using System; class C { static void M() { byte[] bytes = new byte[1]; Span<byte> local1() { return new Span<byte>(bytes); } Span<byte> res = local1(); } } "; CreateCompilationWithMscorlibAndSpanSrc(text).VerifyDiagnostics(); } [Fact, WorkItem(544910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544910")] public void CS1601ERR_MethodArgCantBeRefAny() { // We've changed the text of the error message from // CS1601: Method or delegate parameter cannot be of type 'ref System.TypedReference' // to // CS1601: Cannot make reference to variable of type 'System.TypedReference' // because we use this error message at both the call site and the declaration. // The new wording makes sense in both uses; the former only makes sense at // the declaration site. var text = @" using System; class MyClass { delegate void D(ref TypedReference t1); // CS1601 public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 { var x = __makeref(r3); // CS1601 } public void Test2(out ArgIterator t4) // CS1601 { t4 = default(ArgIterator); } MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (6,23): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t2").WithArguments("System.TypedReference"), // (11,23): error CS1601: Cannot make reference to variable of type 'System.ArgIterator' // public void Test2(out ArgIterator t4) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator t4").WithArguments("System.ArgIterator"), // (16,13): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref RuntimeArgumentHandle r5").WithArguments("System.RuntimeArgumentHandle"), // (5,21): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // delegate void D(ref TypedReference t1); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t1").WithArguments("System.TypedReference"), // (8,17): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // var x = __makeref(r3); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "__makeref(r3)").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionParamCantBeRefAny() { var text = @" class C { public void Goo() { { System.TypedReference _arg = default; void local1(ref System.TypedReference tr) { } // 1601 local1(ref _arg); void local2(in System.TypedReference tr) { } // 1601 local2(in _arg); void local3(out System.TypedReference tr) // 1601 { tr = default; } local3(out _arg); } { System.ArgIterator _arg = default; void local1(ref System.ArgIterator ai) { } // 1601 local1(ref _arg); void local2(in System.ArgIterator ai) { } // 1601 local2(in _arg); void local3(out System.ArgIterator ai) // 1601 { ai = default; } local3(out _arg); } { System.RuntimeArgumentHandle _arg = default; void local1(ref System.RuntimeArgumentHandle ah) { } // 1601 local1(ref _arg); void local2(in System.RuntimeArgumentHandle ah) { } // 1601 local2(in _arg); void local3(out System.RuntimeArgumentHandle ah) // 1601 { ah = default; } local3(out _arg); } } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (8,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local1(ref System.TypedReference tr) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(8, 25), // (11,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local2(in System.TypedReference tr) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(11, 25), // (14,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local3(out System.TypedReference tr) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(14, 25), // (23,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local1(ref System.ArgIterator ai) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(23, 25), // (26,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local2(in System.ArgIterator ai) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(26, 25), // (29,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local3(out System.ArgIterator ai) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(29, 25), // (38,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local1(ref System.RuntimeArgumentHandle ah) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(38, 25), // (41,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local2(in System.RuntimeArgumentHandle ah) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(41, 25), // (44,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local3(out System.RuntimeArgumentHandle ah) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(44, 25)); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void CS1608ERR_CantUseRequiredAttribute() { var text = @"using System.Runtime.CompilerServices; [RequiredAttribute(typeof(object))] class ClassMain { }"; CreateCompilation(text).VerifyDiagnostics( // (3,2): error CS1608: The Required attribute is not permitted on C# types // [RequiredAttribute(typeof(object))] Diagnostic(ErrorCode.ERR_CantUseRequiredAttribute, "RequiredAttribute").WithLocation(3, 2)); } [Fact] public void CS1614ERR_AmbiguousAttribute() { var text = @"using System; class A : Attribute { } class AAttribute : Attribute { } [A][@A][AAttribute] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbiguousAttribute, Line = 4, Column = 2 }); } [Fact] public void CS0214ERR_RequiredInUnsafeContext() { var text = @"struct C { public fixed int ab[10]; // CS0214 } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); // (3,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed string ab[10]; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "ab[10]"); } [Fact] public void CS1642ERR_FixedNotInStruct() { var text = @"unsafe class C { fixed int a[10]; // CS1642 }"; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,15): error CS1642: Fixed size buffer fields may only be members of structs // fixed int a[10]; // CS1642 Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a")); } [Fact] public void CS1663ERR_IllegalFixedType() { var text = @"unsafe struct C { fixed string ab[10]; // CS1663 }"; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // fixed string ab[10]; // CS1663 Diagnostic(ErrorCode.ERR_IllegalFixedType, "string")); } [WorkItem(545353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545353")] [Fact] public void CS1664ERR_FixedOverflow() { // set Allow unsafe code = true var text = @"public unsafe struct C { unsafe private fixed long test_1[1073741825]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,38): error CS1664: Fixed size buffer of length '1073741825' and type 'long' is too big // unsafe private fixed long test_1[1073741825]; Diagnostic(ErrorCode.ERR_FixedOverflow, "1073741825").WithArguments("1073741825", "long")); } [WorkItem(545353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545353")] [Fact] public void CS1665ERR_InvalidFixedArraySize() { var text = @"unsafe struct S { public unsafe fixed int A[0]; // CS1665 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS1665: Fixed size buffers must have a length greater than zero // public unsafe fixed int A[0]; // CS1665 Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "0")); } [WorkItem(546922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546922")] [Fact] public void CS1665ERR_InvalidFixedArraySizeNegative() { var text = @"unsafe struct S { public unsafe fixed int A[-1]; // CS1665 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "-1")); } [Fact()] public void CS0443ERR_InvalidFixedArraySizeNotSpecified() { var text = @"unsafe struct S { public unsafe fixed int A[]; // CS0443 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS0443: Syntax error; value expected // public unsafe fixed int A[]; // CS0443 Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void CS1003ERR_InvalidFixedArrayMultipleDimensions() { var text = @"unsafe struct S { public unsafe fixed int A[2,2]; // CS1003,CS1001 public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,33): error CS1002: ; expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_SemicolonExpected, "["), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,36): error CS1519: Invalid token ';' in class, struct, or interface member declaration // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";"), // (3,30): error CS7092: A fixed buffer may only have one dimension. // public unsafe fixed int A[2,2]; // CS1003,CS1001 Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[2,2]")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested() { var text = @"unsafe struct S { unsafe class Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; //Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferInner[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferInner")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested_2() { var text = @"unsafe class S { unsafe struct Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; // Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferOuter[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferOuter")); } [Fact] public void CS0133ERR_InvalidFixedBufferCountFromField() { var text = @"unsafe struct s { public static int var1 = 10; public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,34): error CS0133: The expression being assigned to 's._Type3' must be constant // public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "var1").WithArguments("s._Type3")); } [Fact] public void CS1663ERR_InvalidFixedBufferUsingGenericType() { var text = @"unsafe struct Err_FixedBufferDeclarationUsingGeneric<t> { public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "t")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypes() { var text = @"unsafe struct s { public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) public fixed int _Type2[true]; // error CS00029 public fixed int _Type3[""true""]; // error CS00029 public fixed int _Type4[System.Convert.ToInt32(@""1"")]; // error CS0133 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,33): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.2").WithArguments("double", "int"), // (4,33): error CS0029: Cannot implicitly convert type 'bool' to 'int' // public fixed int _Type2[true]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "true").WithArguments("bool", "int"), // (5,33): error CS0029: Cannot implicitly convert type 'string' to 'int' // public fixed int _Type3["true"]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""true""").WithArguments("string", "int"), // (6,33): error CS0133: The expression being assigned to 's._Type4' must be constant // public fixed int _Type4[System.Convert.ToInt32(@"1")]; // error CS0133 Diagnostic(ErrorCode.ERR_NotConstantExpression, @"System.Convert.ToInt32(@""1"")").WithArguments("s._Type4")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypesUserDefinedTypes() { var text = @"unsafe struct s { public fixed goo _bufferGoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } struct goo { public int ABC; } class bar { public bool ABC = true; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed goo _bufferGoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "goo"), // (4,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "bar"), // (9,20): warning CS0649: Field 'goo.ABC' is never assigned to, and will always have its default value 0 // public int ABC; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ABC").WithArguments("goo.ABC", "0")); } [Fact] public void C1666ERR_InvalidFixedBufferInUnfixedContext() { var text = @" unsafe struct s { private fixed ushort _e_res[4]; void Error_UsingFixedBuffersWithThis() { ushort c = this._e_res; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,24): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. // ushort c = this._e_res; Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "this._e_res")); } [Fact] public void CS0029ERR_InvalidFixedBufferUsageInLocal() { //Some additional errors generated but the key ones from native are here. var text = @"unsafe struct s { //Use as local rather than field with unsafe on method // Incorrect usage of fixed buffers in method bodies try to use as a local static unsafe void Error_UseAsLocal() { //Invalid In Use as Local fixed bool _buffer[2]; // error CS1001: Identifier expected } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,15): error CS1003: Syntax error, '(' expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_SyntaxError, "bool").WithArguments("(", "bool"), // (8,27): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CStyleArray, "[2]"), // (8,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "2"), // (8,30): error CS1026: ) expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CloseParenExpected, ";"), // (8,30): warning CS0642: Possible mistaken empty statement // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_BadFixedInitType, "_buffer[2]"), // (8,20): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_FixedMustInit, "_buffer[2]")); } [Fact()] public void CS1667ERR_AttributeNotOnAccessor() { var text = @"using System; public class C { private int i; public int ObsoleteProperty { [Obsolete] // CS1667 get { return i; } [System.Diagnostics.Conditional(""Bernard"")] set { i = value; } } public static void Main() { } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (10,10): error CS1667: Attribute 'System.Diagnostics.Conditional' is not valid on property or event accessors. It is only valid on 'class, method' declarations. // [System.Diagnostics.Conditional("Bernard")] Diagnostic(ErrorCode.ERR_AttributeNotOnAccessor, "System.Diagnostics.Conditional").WithArguments("System.Diagnostics.Conditional", "class, method") ); } [Fact] public void CS1689ERR_ConditionalOnNonAttributeClass() { var text = @"[System.Diagnostics.Conditional(""A"")] // CS1689 class MyClass {} "; CreateCompilation(text).VerifyDiagnostics( // (1,2): error CS1689: Attribute 'System.Diagnostics.Conditional' is only valid on methods or attribute classes // [System.Diagnostics.Conditional("A")] // CS1689 Diagnostic(ErrorCode.ERR_ConditionalOnNonAttributeClass, @"System.Diagnostics.Conditional(""A"")").WithArguments("System.Diagnostics.Conditional").WithLocation(1, 2)); } // CS17ERR_DuplicateImport: See ReferenceManagerTests.CS17ERR_DuplicateImport // CS1704ERR_DuplicateImportSimple: See ReferenceManagerTests.CS1704ERR_DuplicateImportSimple [Fact(Skip = "530901"), WorkItem(530901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530901")] public void CS1705ERR_AssemblyMatchBadVersion() { // compile with: /target:library /out:c:\\cs1705.dll /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""1.0"")] public class A { public void M1() {} public class N1 {} public void M2() {} public class N2 {} } public class C1 {} public class C2 {} "; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); // compile with: /target:library /out:cs1705.dll /keyfile:mykey.snk var text2 = @"using System.Reflection; [assembly:AssemblyVersion(""2.0"")] public class A { public void M2() {} public class N2 {} public void M1() {} public class N1 {} } public class C2 {} public class C1 {} "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); // compile with: /target:library /r:A2=c:\\CS1705.dll /r:A1=CS1705.dll var text3 = @"extern alias A1; extern alias A2; using a1 = A1::A; using a2 = A2::A; using n1 = A1::A.N1; using n2 = A2::A.N2; public class Ref { public static a1 A1() { return new a1(); } public static a2 A2() { return new a2(); } public static A1::C1 M1() { return new A1::C1(); } public static A2::C2 M2() { return new A2::C2(); } public static n1 N1() { return new a1.N1(); } public static n2 N2() { return new a2.N2(); } } "; var tree3 = SyntaxFactory.ParseCompilationUnit(text3); // compile with: /reference:c:\\CS1705.dll /reference:CS1705_c.dll var text = @"class Tester { static void Main() { Ref.A1().M1(); Ref.A2().M2(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AssemblyMatchBadVersion, Line = 2, Column = 12 }); } [Fact] public void CS1715ERR_CantChangeTypeOnOverride() { var text = @"abstract public class Base { abstract public int myProperty { get; set; } } public class Derived : Base { int myField; public override double myProperty // CS1715 { get { return myField; } set { myField= 1; } } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 10, Column = 14 }, //Base.myProperty.get not impl new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 10, Column = 14 }, //Base.myProperty.set not impl // COMPARE: InheritanceBindingTests.TestNoPropertyToOverride new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 13, Column = 28 } //key error, property type changed ); } [Fact] public void CS1716ERR_DoNotUseFixedBufferAttr() { var text = @" using System.Runtime.CompilerServices; public struct UnsafeStruct { [FixedBuffer(typeof(int), 4)] // CS1716 unsafe public int aField; } public class TestUnsafe { static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,6): error CS1716: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead. // [FixedBuffer(typeof(int), 4)] // CS1716 Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttr, "FixedBuffer").WithLocation(6, 6)); } [Fact] public void CS1721ERR_NoMultipleInheritance01() { var text = @"namespace NS { public class A { } public class B { } public class C : B { } public class MyClass : A, A { } // CS1721 public class MyClass2 : A, B { } // CS1721 public class MyClass3 : C, A { } // CS1721 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 7, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 8, Column = 32 }); } [Fact] public void CS1722ERR_BaseClassMustBeFirst01() { var text = @"namespace NS { public class A { } interface I { } interface IGoo<T> : I { } public class MyClass : I, A { } // CS1722 public class MyClass2 : A, I { } // OK class Test { class C : IGoo<int>, A , I { } // CS1722 } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 7, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 30 }); } [Fact(), WorkItem(530393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530393")] public void CS1724ERR_InvalidDefaultCharSetValue() { var text = @" using System.Runtime.InteropServices; [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 class C { [DllImport(""F.Dll"")] extern static void FW1Named(); static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,34): error CS0591: Invalid value for argument to 'DefaultCharSetAttribute' attribute // [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(CharSet)42").WithArguments("DefaultCharSetAttribute") ); } [Fact, WorkItem(1116455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116455")] public void CS1725ERR_FriendAssemblyBadArgs() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Test, Version=*"")] // ok [assembly: InternalsVisibleTo(""Test, PublicKeyToken=*"")] // ok [assembly: InternalsVisibleTo(""Test, Culture=*"")] // ok [assembly: InternalsVisibleTo(""Test, Retargetable=*"")] // ok [assembly: InternalsVisibleTo(""Test, ContentType=*"")] // ok [assembly: InternalsVisibleTo(""Test, Version=."")] // ok [assembly: InternalsVisibleTo(""Test, Version=.."")] // ok [assembly: InternalsVisibleTo(""Test, Version=..."")] // ok [assembly: InternalsVisibleTo(""Test, Version=1"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")] // error [assembly: InternalsVisibleTo(""Test, CuLTure=EN"")] // error [assembly: InternalsVisibleTo(""Test, PublicKeyToken=null"")] // ok "; // Tested against Dev12 CreateCompilation(text).VerifyDiagnostics( // (12,12): error CS1725: Friend assembly reference 'Test, Version=1' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1"")").WithArguments("Test, Version=1").WithLocation(12, 12), // (13,12): error CS1725: Friend assembly reference 'Test, Version=1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.*"")").WithArguments("Test, Version=1.*").WithLocation(13, 12), // (14,12): error CS1725: Friend assembly reference 'Test, Version=1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.*"")").WithArguments("Test, Version=1.1.*").WithLocation(14, 12), // (15,12): error CS1725: Friend assembly reference 'Test, Version=1.1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.1.*"")").WithArguments("Test, Version=1.1.1.*").WithLocation(15, 12), // (16,12): error CS1725: Friend assembly reference 'Test, ProcessorArchitecture=MSIL' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")").WithArguments("Test, ProcessorArchitecture=MSIL").WithLocation(16, 12), // (17,12): error CS1725: Friend assembly reference 'Test, CuLTure=EN' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, CuLTure=EN"")").WithArguments("Test, CuLTure=EN").WithLocation(17, 12)); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant01() { var text = @"class A { static int Age; public void Goo(int Para1 = Age) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,33): error CS1736: Default parameter value for 'Para1' must be a compile-time constant // public void Goo(int Para1 = Age) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Age").WithArguments("Para1"), // (3,16): warning CS0169: The field 'A.Age' is never used // static int Age; Diagnostic(ErrorCode.WRN_UnreferencedField, "Age").WithArguments("A.Age") ); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant02() { var source = @"class C { object this[object x, object y = new C()] { get { return null; } set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,38): error CS1736: Default parameter value for 'y' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new C()").WithArguments("y").WithLocation(3, 38)); } [Fact, WorkItem(542401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542401")] public void CS1736ERR_DefaultValueMustBeConstant_1() { var text = @" class NamedExample { static int y = 1; static void Main(string[] args) { } int CalculateBMI(int weight, int height = y) { return (weight * 7) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (9,47): error CS1736: Default parameter value for 'height' must be a compile-time constant // int CalculateBMI(int weight, int height = y) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "y").WithArguments("height"), // (4,16): warning CS0414: The field 'NamedExample.y' is assigned but its value is never used // static int y = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "y").WithArguments("NamedExample.y") ); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @"class A { public void Goo(int Para1 = 1, int Para2) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1737, Line = 3, Column = 45 }); } [Fact] public void CS1741ERR_RefOutDefaultValue() { var text = @"class A { public void Goo(ref int Para1 = 1) { } public void Goo1(out int Para2 = 1) { Para2 = 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1741, Line = 3, Column = 21 }, new ErrorDescription { Code = 1741, Line = 5, Column = 22 }); } [Fact] public void CS17ERR_DefaultValueForExtensionParameter() { var text = @"static class C { static void M1(object o = null) { } static void M2(this object o = null) { } static void M3(object o, this int i = 0) { } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (4,20): error CS17: Cannot specify a default value for the 'this' parameter Diagnostic(ErrorCode.ERR_DefaultValueForExtensionParameter, "this").WithLocation(4, 20), // (5,30): error CS1100: Method 'M3' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M3").WithLocation(5, 30)); } [Fact] public void CS1745ERR_DefaultValueUsedWithAttributes() { var text = @" using System.Runtime.InteropServices; class A { public void goo([OptionalAttribute]int p = 1) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,22): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void goo([OptionalAttribute]int p = 1) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "OptionalAttribute") ); } [Fact] public void CS1747ERR_NoPIAAssemblyMissingAttribute() { //csc program.cs /l:"C:\MissingPIAAttributes.dll var text = @"public class Test { static int Main(string[] args) { return 1; } }"; var ref1 = TestReferences.SymbolsTests.NoPia.Microsoft.VisualStudio.MissingPIAAttributes.WithEmbedInteropTypes(true); CreateCompilation(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1747: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.GuidAttribute").WithLocation(1, 1), // error CS1759: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute").WithLocation(1, 1)); } [WorkItem(620366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620366")] [Fact] public void CS1748ERR_NoCanonicalView() { var textdll = @" using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""A55E0B17-2558-447D-B786-84682CBEF136"")] [assembly: BestFitMapping(false)] [ComImport, Guid(""E245C65D-2448-447A-B786-64682CBEF133"")] [TypeIdentifier(""E245C65D-2448-447A-B786-64682CBEF133"", ""IMyInterface"")] public interface IMyInterface { void Method(int n); } public delegate void DelegateWithInterface(IMyInterface value); public delegate void DelegateWithInterfaceArray(IMyInterface[] ary); public delegate IMyInterface DelegateRetInterface(); public delegate DelegateRetInterface DelegateRetDelegate(DelegateRetInterface d); "; var text = @" class Test { static void Main() { } public static void MyDelegate02(IMyInterface[] ary) { } } "; var comp1 = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp1); CreateCompilation(text, references: new MetadataReference[] { ref1 }).VerifyDiagnostics( // (77): error CS0246: The type or namespace name 'IMyInterface' could not be found (are you missing a using directive or an assembly reference?) // public static void MyDelegate02(IMyInterface[] ary) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IMyInterface").WithArguments("IMyInterface") ); } [Fact] public void CS1750ERR_NoConversionForDefaultParam() { var text = @"public class Generator { public void Show<T>(string msg = ""Number"", T value = null) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1750, Line = 3, Column = 50 }); } [Fact] public void CS1751ERR_DefaultValueForParamsParameter() { // The native compiler only produces one error here -- that // the default value on "params" is illegal. However it // seems reasonable to produce one error for each bad param. var text = @"class MyClass { public void M7(int i = null, params string[] values = ""test"") { } static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // 'i': A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'int' new ErrorDescription { Code = 1750, Line = 3, Column = 24 }, // 'params': error CS1751: Cannot specify a default value for a parameter array new ErrorDescription { Code = 1751, Line = 3, Column = 34 }); } [ConditionalFact(typeof(DesktopOnly))] public void CS1754ERR_NoPIANestedType() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyClass { public struct NestedClass { public string Name; } } } "; var text = @"public class Test { public static void Main() { var S = new NS.MyClass.NestedClass(); System.Console.Write(S); } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoPIANestedType, "NestedClass").WithArguments("NS.MyClass.NestedClass")); } [Fact()] public void CS1755ERR_InvalidTypeIdentifierConstructor() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { [TypeIdentifier(""Goo2"", ""Bar2"")] public delegate void MyDel(); } "; var text = @" public class Test { event NS.MyDel e; public static void Main() { } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // (4,14): error CS0234: The type or namespace name 'MyDel' does not exist in the namespace 'NS' (are you missing an assembly reference?) // event NS.MyDel e; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MyDel").WithArguments("MyDel", "NS"), // (4,20): warning CS0067: The event 'Test.e' is never used // event NS.MyDel e; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("Test.e")); //var comp1 = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(new List<string>() { text }, new List<MetadataReference>() { ref1 }, // new ErrorDescription { Code = 1755, Line = 4, Column = 14 }); } [ConditionalFact(typeof(DesktopOnly))] public void CS1757ERR_InteropStructContainsMethods() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyStruct { private int _age; public string Name; } } "; var text = @"public class Test { public static void Main() { NS.MyStruct S = new NS.MyStruct(); System.Console.Write(S); } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); var comp1 = CreateCompilation(text, new[] { ref1 }); comp1.VerifyEmitDiagnostics( // (5,24): error CS1757: Embedded interop struct 'NS.MyStruct' can contain only public instance fields. // NS.MyStruct S = new NS.MyStruct(); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "new NS.MyStruct()").WithArguments("NS.MyStruct")); } [Fact] public void CS1754ERR_NoPIANestedType_2() { //vbc /t:library PIA.vb //csc /l:PIA.dll Program.cs var textdll = @"Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib(""GeneralPIA.dll"")> <Assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedClass Class InnerClass End Class End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedStructure Structure InnerStructure End Structure End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedEnum Enum InnerEnum Value1 End Enum End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedDelegate Delegate Sub InnerDelegate() End Interface Public Structure NestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Structure Public Structure NestedClass Class InnerClass End Class End Structure Public Structure NestedStructure Structure InnerStructure End Structure End Structure Public Structure NestedEnum Enum InnerEnum Value1 End Enum End Structure Public Structure NestedDelegate Delegate Sub InnerDelegate() End Structure"; var text = @"public class Program { public static void Main() { INestedInterface.InnerInterface s1 = null; INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); INestedDelegate.InnerDelegate s5 = null; } }"; var vbcomp = VisualBasic.VisualBasicCompilation.Create( "Test", new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(textdll) }, new[] { MscorlibRef_v4_0_30316_17626 }, new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var ref1 = vbcomp.EmitToImageReference(embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // (5,26): error CS1754: Type 'INestedInterface.InnerInterface' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerInterface").WithArguments("INestedInterface.InnerInterface"), // (6,26): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (6,71): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (7,21): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (7,56): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (8,25): error CS1754: Type 'INestedDelegate.InnerDelegate' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerDelegate").WithArguments("INestedDelegate.InnerDelegate"), // (5,41): warning CS0219: The variable 's1' is assigned but its value is never used // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1"), // (6,41): warning CS0219: The variable 's3' is assigned but its value is never used // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s3").WithArguments("s3"), // (71): warning CS0219: The variable 's4' is assigned but its value is never used // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s4").WithArguments("s4"), // (8,39): warning CS0219: The variable 's5' is assigned but its value is never used // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s5").WithArguments("s5")); } [Fact] public void CS17ERR_NotNullRefDefaultParameter() { var text = @" public static class ErrorCode { // We do not allow constant conversions from string to object in a default parameter initializer static void M1(object x = ""hello"") {} // We do not allow boxing conversions to object in a default parameter initializer static void M2(System.ValueType y = 123) {} }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // (5,25): error CS17: 'x' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 5, Column = 25 }, // (75): error CS17: 'y' is of type 'System.ValueType'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 7, Column = 35 }); } [WorkItem(619266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619266")] [Fact(Skip = "619266")] public void CS1768ERR_GenericsUsedInNoPIAType() { // add dll and make it embed var textdll = @"using System; using System.Collections.Generic; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace ClassLibrary3 { [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed5"")] public interface IGoo { IBar<string> goo(); } [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed6"")] public interface IBar<T> { List<IGoo> GetList(); } } "; var text = @" using System.Collections.Generic; using ClassLibrary3; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { IGoo x = (IGoo)new object(); } } class goo : IBar<string>, IGoo { public List<string> GetList() { throw new NotImplementedException(); } List<IGoo> IBar<string>.GetList() { throw new NotImplementedException(); } } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_GenericsUsedInNoPIAType)); } [Fact, WorkItem(6186, "https://github.com/dotnet/roslyn/issues/6186")] public void CS1770ERR_NoConversionForNubDefaultParam() { var text = @"using System; class MyClass { public enum E { None } // No error: public void Goo1(int? x = default(int)) { } public void Goo2(E? x = default(E)) { } public void Goo3(DateTime? x = default(DateTime?)) { } public void Goo4(DateTime? x = new DateTime?()) { } // Error: public void Goo11(DateTime? x = default(DateTime)) { } public void Goo12(DateTime? x = new DateTime()) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,33): error CS1770: A value of type 'DateTime' cannot be used as default parameter for nullable parameter 'x' because 'DateTime' is not a simple type // public void Goo11(DateTime? x = default(DateTime)) { } Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("System.DateTime", "x").WithLocation(13, 33), // (14,33): error CS1770: A value of type 'DateTime' cannot be used as default parameter for nullable parameter 'x' because 'DateTime' is not a simple type // public void Goo12(DateTime? x = new DateTime()) { } Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("System.DateTime", "x").WithLocation(14, 33) ); } [Fact] public void CS1908ERR_DefaultValueTypeMustMatch() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Bad([Optional] [DefaultParameterValue(""true"")] bool b); // CS1908 } "; CreateCompilation(text).VerifyDiagnostics( // (4,26): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } // Dev10 reports CS1909: The DefaultValue attribute is not applicable on parameters of type '{0}'. // for parameters of type System.Type or array even though there is no reason why null couldn't be specified in DPV. // We report CS1910 if DPV has an argument of type System.Type or array like Dev10 does except for we do so instead // of CS1909 when non-null is passed. [Fact] public void CS1909ERR_DefaultValueBadValueType_Array_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]int[] arr1); } "; // Dev10 reports CS1909, we don't CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Array() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(new int[] { 1, 2 })]object a); void Test2([DefaultParameterValue(new int[] { 1, 2 })]int[] a); void Test3([DefaultParameterValue(new int[0])]int[] a); } "; // CS1910 CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (5,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (6,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]")); } [Fact] public void CS1909ERR_DefaultValueBadValueType_Type_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]System.Type t); } "; // Dev10 reports CS1909, we don't CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValue_Generics() { var text = @"using System.Runtime.InteropServices; public class C { } public interface ISomeInterface { void Test1<T>([DefaultParameterValue(null)]T t); // error void Test2<T>([DefaultParameterValue(null)]T t) where T : C; // OK void Test3<T>([DefaultParameterValue(null)]T t) where T : class; // OK void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error } "; CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test1<T>([DefaultParameterValue(null)]T t); // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (9,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type1() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]object t); // CS1910 } "; CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type2() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]System.Type t); // CS1910 } "; CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1961ERR_UnexpectedVariance() { var text = @"interface Goo<out T> { T Bar(); void Baz(T t); }"; CreateCompilation(text).VerifyDiagnostics( // (4,14): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'Goo<T>.Baz(T)'. 'T' is covariant. // void Baz(T t); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("Goo<T>.Baz(T)", "T", "covariant", "contravariantly").WithLocation(4, 14)); } [Fact] public void CS1965ERR_DeriveFromDynamic() { var text = @"public class ErrorCode : dynamic { }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (1,26): error CS1965: 'ErrorCode': cannot derive from the dynamic type Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("ErrorCode")); } [Fact, WorkItem(552740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552740")] public void CS1966ERR_DeriveFromConstructedDynamic() { var text = @" interface I<T> { } class C<T> { public enum D { } } class E1 : I<dynamic> {} class E2 : I<C<dynamic>.D*[]> {} "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,12): error CS1966: 'E2': cannot implement a dynamic interface 'I<C<dynamic>.D*[]>' // class E2 : I<C<dynamic>.D*[]> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<C<dynamic>.D*[]>").WithArguments("E2", "I<C<dynamic>.D*[]>"), // (10,12): error CS1966: 'E1': cannot implement a dynamic interface 'I<dynamic>' // class E1 : I<dynamic> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<dynamic>").WithArguments("E1", "I<dynamic>")); } [Fact] public void CS1967ERR_DynamicTypeAsBound() { var source = @"delegate void D<T>() where T : dynamic;"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (1,32): error CS1967: Constraint cannot be the dynamic type Diagnostic(ErrorCode.ERR_DynamicTypeAsBound, "dynamic")); } [Fact] public void CS1968ERR_ConstructedDynamicTypeAsBound() { var source = @"interface I<T> { } struct S<T> { internal delegate void D<U>(); } class A<T> { } class B<T, U> where T : A<S<T>.D<dynamic>>, I<dynamic[]> where U : I<S<dynamic>.D<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (8,15): error CS1968: Constraint cannot be a dynamic type 'A<S<T>.D<dynamic>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "A<S<T>.D<dynamic>>").WithArguments("A<S<T>.D<dynamic>>").WithLocation(8, 15), // (8,35): error CS1968: Constraint cannot be a dynamic type 'I<dynamic[]>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<dynamic[]>").WithArguments("I<dynamic[]>").WithLocation(8, 35), // (9,15): error CS1968: Constraint cannot be a dynamic type 'I<S<dynamic>.D<T>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<S<dynamic>.D<T>>").WithArguments("I<S<dynamic>.D<T>>").WithLocation(9, 15)); } // Instead of CS1982 ERR_DynamicNotAllowedInAttribute we report CS0181 ERR_BadAttributeParamType [Fact] public void CS1982ERR_DynamicNotAllowedInAttribute_NoError() { var text = @" using System; public class C<T> { public enum D { A } } [A(T = typeof(dynamic[]))] // Dev11 reports error, but this should be ok [A(T = typeof(C<dynamic>))] [A(T = typeof(C<dynamic>[]))] [A(T = typeof(C<dynamic>.D[]))] [A(T = typeof(C<dynamic>.D*[]))] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class A : Attribute { public Type T; } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [Fact] public void CS7021ERR_NamespaceNotAllowedInScript() { var text = @" namespace N1 { class A { public int Goo() { return 2; }} } "; var expectedDiagnostics = new[] { // (2,1): error CS7021: You cannot declare namespace in script code // namespace N1 Diagnostic(ErrorCode.ERR_NamespaceNotAllowedInScript, "namespace").WithLocation(2, 1) }; CreateCompilationWithMscorlib45(new[] { Parse(text, options: TestOptions.Script) }).VerifyDiagnostics(expectedDiagnostics); } [Fact] public void CS8050ERR_InitializerOnNonAutoProperty() { var source = @"public class C { int A { get; set; } = 1; int I { get { throw null; } set { } } = 1; static int S { get { throw null; } set { } } = 1; protected int P { get { throw null; } set { } } = 1; }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS8050: Only auto-implemented properties can have initializers. // int I { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("C.I").WithLocation(5, 9), // (6,16): error CS8050: Only auto-implemented properties can have initializers. // static int S { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "S").WithArguments("C.S").WithLocation(6, 16), // (7,19): error CS8050: Only auto-implemented properties can have initializers. // protected int P { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "P").WithArguments("C.P").WithLocation(7, 19) ); } [Fact] public void ErrorTypeCandidateSymbols1() { var text = @" class A { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.TypeWithAnnotations; Assert.Equal(SymbolKind.ErrorType, fieldType.Type.Kind); Assert.Equal("B", fieldType.Type.Name); var errorFieldType = (ErrorTypeSymbol)fieldType.Type; Assert.Equal(CandidateReason.None, errorFieldType.CandidateReason); Assert.Equal(0, errorFieldType.CandidateSymbols.Length); } [Fact] public void ErrorTypeCandidateSymbols2() { var text = @" class C { private class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single(); var classB = (NamedTypeSymbol)classC.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Inaccessible, errorFieldType.CandidateReason); Assert.Equal(1, errorFieldType.CandidateSymbols.Length); Assert.Equal(classB, errorFieldType.CandidateSymbols[0]); } [Fact] public void ErrorTypeCandidateSymbols3() { var text = @" using N1; using N2; namespace N1 { class B {} } namespace N2 { class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var ns1 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N1").Single(); var ns2 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N2").Single(); var classBinN1 = (NamedTypeSymbol)ns1.GetTypeMembers("B").Single(); var classBinN2 = (NamedTypeSymbol)ns2.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Ambiguous, errorFieldType.CandidateReason); Assert.Equal(2, errorFieldType.CandidateSymbols.Length); Assert.True((TypeSymbol.Equals(classBinN1, (TypeSymbol)errorFieldType.CandidateSymbols[0], TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(classBinN2, (TypeSymbol)errorFieldType.CandidateSymbols[1], TypeCompareKind.ConsiderEverything2)) || (TypeSymbol.Equals(classBinN2, (TypeSymbol)errorFieldType.CandidateSymbols[0], TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(classBinN1, (TypeSymbol)errorFieldType.CandidateSymbols[1], TypeCompareKind.ConsiderEverything2)), "CandidateSymbols must by N1.B and N2.B in some order"); } #endregion #region "Symbol Warning Tests" /// <summary> /// current error 104 /// </summary> [Fact] public void CS0105WRN_DuplicateUsing01() { var text = @"using System; using System; namespace Goo.Bar { class A { } } namespace testns { using Goo.Bar; using System; using Goo.Bar; class B : A { } }"; CreateCompilation(text).VerifyDiagnostics( // (2,7): warning CS0105: The using directive for 'System' appeared previously in this namespace // using System; Diagnostic(ErrorCode.WRN_DuplicateUsing, "System").WithArguments("System"), // (13,11): warning CS0105: The using directive for 'Goo.Bar' appeared previously in this namespace // using Goo.Bar; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Goo.Bar").WithArguments("Goo.Bar"), // (1,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (12,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (13,5): info CS8019: Unnecessary using directive. // using Goo.Bar; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Goo.Bar;")); // TODO... // var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0108WRN_NewRequired01() { var text = @"using System; namespace x { public class clx { public int i = 1; } public class cly : clx { public static int i = 2; // CS0108, use the new keyword public static void Main() { Console.WriteLine(i); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 27, IsWarning = true }); } [Fact] public void CS0108WRN_NewRequired02() { var source = @"class A { public static void P() { } public static void Q() { } public void R() { } public void S() { } public static int T { get; set; } public static int U { get; set; } public int V { get; set; } public int W { get; set; } } class B : A { public static int P { get; set; } // CS0108 public int Q { get; set; } // CS0108 public static int R { get; set; } // CS0108 public int S { get; set; } // CS0108 public static void T() { } // CS0108 public void U() { } // CS0108 public static void V() { } // CS0108 public void W() { } // CS0108 } "; CreateCompilation(source).VerifyDiagnostics( // (15,16): warning CS0108: 'B.Q' hides inherited member 'A.Q()'. Use the new keyword if hiding was intended. // public int Q { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "Q").WithArguments("B.Q", "A.Q()").WithLocation(15, 16), // (16,23): warning CS0108: 'B.R' hides inherited member 'A.R()'. Use the new keyword if hiding was intended. // public static int R { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "R").WithArguments("B.R", "A.R()").WithLocation(16, 23), // (17,16): warning CS0108: 'B.S' hides inherited member 'A.S()'. Use the new keyword if hiding was intended. // public int S { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "S").WithArguments("B.S", "A.S()").WithLocation(17, 16), // (18,24): warning CS0108: 'B.T()' hides inherited member 'A.T'. Use the new keyword if hiding was intended. // public static void T() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("B.T()", "A.T").WithLocation(18, 24), // (19,17): warning CS0108: 'B.U()' hides inherited member 'A.U'. Use the new keyword if hiding was intended. // public void U() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "U").WithArguments("B.U()", "A.U").WithLocation(19, 17), // (20,24): warning CS0108: 'B.V()' hides inherited member 'A.V'. Use the new keyword if hiding was intended. // public static void V() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "V").WithArguments("B.V()", "A.V").WithLocation(20, 24), // (21,17): warning CS0108: 'B.W()' hides inherited member 'A.W'. Use the new keyword if hiding was intended. // public void W() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "W").WithArguments("B.W()", "A.W").WithLocation(21, 17), // (14,23): warning CS0108: 'B.P' hides inherited member 'A.P()'. Use the new keyword if hiding was intended. // public static int P { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "P").WithArguments("B.P", "A.P()").WithLocation(14, 23)); } [WorkItem(539624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539624")] [Fact] public void CS0108WRN_NewRequired03() { var text = @" class BaseClass { public int MyMeth(int intI) { return intI; } } class MyClass : BaseClass { public static int MyMeth(int intI) // CS0108 { return intI + 1; } } class SBase { protected static void M() {} } class DClass : SBase { protected void M() {} // CS0108 } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 13, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 26, Column = 20, IsWarning = true }); } [WorkItem(540459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540459")] [Fact] public void CS0108WRN_NewRequired04() { var text = @" class A { public void f() { } } class B: A { } class C : B { public int f = 3; //CS0108 } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): warning CS0108: 'C.f' hides inherited member 'A.f()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "f").WithArguments("C.f", "A.f()")); } [Fact] public void CS0108WRN_NewRequired05() { var text = @" class A { public static void SM1() { } public static void SM2() { } public static void SM3() { } public static void SM4() { } public void IM1() { } public void IM2() { } public void IM3() { } public void IM4() { } public static int SP1 { get; set; } public static int SP2 { get; set; } public static int SP3 { get; set; } public static int SP4 { get; set; } public int IP1 { get; set; } public int IP2 { get; set; } public int IP3 { get; set; } public int IP4 { get; set; } public static event System.Action SE1; public static event System.Action SE2; public static event System.Action SE3; public static event System.Action SE4; public event System.Action IE1{ add { } remove { } } public event System.Action IE2{ add { } remove { } } public event System.Action IE3{ add { } remove { } } public event System.Action IE4{ add { } remove { } } } class B : A { public static int SM1 { get; set; } //CS0108 public int SM2 { get; set; } //CS0108 public static event System.Action SM3; //CS0108 public event System.Action SM4{ add { } remove { } } //CS0108 public static int IM1 { get; set; } //CS0108 public int IM2 { get; set; } //CS0108 public static event System.Action IM3; //CS0108 public event System.Action IM4{ add { } remove { } } //CS0108 public static void SP1() { } //CS0108 public void SP2() { } //CS0108 public static event System.Action SP3; //CS0108 public event System.Action SP4{ add { } remove { } } //CS0108 public static void IP1() { } //CS0108 public void IP2() { } //CS0108 public static event System.Action IP3; //CS0108 public event System.Action IP4{ add { } remove { } } //CS0108 public static void SE1() { } //CS0108 public void SE2() { } //CS0108 public static int SE3 { get; set; } //CS0108 public int SE4 { get; set; } //CS0108 public static void IE1() { } //CS0108 public void IE2() { } //CS0108 public static int IE3 { get; set; } //CS0108 public int IE4 { get; set; } //CS0108 }"; CreateCompilation(text).VerifyDiagnostics( // (36,23): warning CS0108: 'B.SM1' hides inherited member 'A.SM1()'. Use the new keyword if hiding was intended. // public static int SM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM1").WithArguments("B.SM1", "A.SM1()"), // (37,16): warning CS0108: 'B.SM2' hides inherited member 'A.SM2()'. Use the new keyword if hiding was intended. // public int SM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM2").WithArguments("B.SM2", "A.SM2()"), // (38,39): warning CS0108: 'B.SM3' hides inherited member 'A.SM3()'. Use the new keyword if hiding was intended. // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM3").WithArguments("B.SM3", "A.SM3()"), // (39,32): warning CS0108: 'B.SM4' hides inherited member 'A.SM4()'. Use the new keyword if hiding was intended. // public event System.Action SM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM4").WithArguments("B.SM4", "A.SM4()"), // (41,23): warning CS0108: 'B.IM1' hides inherited member 'A.IM1()'. Use the new keyword if hiding was intended. // public static int IM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM1").WithArguments("B.IM1", "A.IM1()"), // (42,16): warning CS0108: 'B.IM2' hides inherited member 'A.IM2()'. Use the new keyword if hiding was intended. // public int IM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM2").WithArguments("B.IM2", "A.IM2()"), // (43,39): warning CS0108: 'B.IM3' hides inherited member 'A.IM3()'. Use the new keyword if hiding was intended. // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM3").WithArguments("B.IM3", "A.IM3()"), // (44,32): warning CS0108: 'B.IM4' hides inherited member 'A.IM4()'. Use the new keyword if hiding was intended. // public event System.Action IM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM4").WithArguments("B.IM4", "A.IM4()"), // (46,24): warning CS0108: 'B.SP1()' hides inherited member 'A.SP1'. Use the new keyword if hiding was intended. // public static void SP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP1").WithArguments("B.SP1()", "A.SP1"), // (47,17): warning CS0108: 'B.SP2()' hides inherited member 'A.SP2'. Use the new keyword if hiding was intended. // public void SP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP2").WithArguments("B.SP2()", "A.SP2"), // (48,39): warning CS0108: 'B.SP3' hides inherited member 'A.SP3'. Use the new keyword if hiding was intended. // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP3").WithArguments("B.SP3", "A.SP3"), // (49,32): warning CS0108: 'B.SP4' hides inherited member 'A.SP4'. Use the new keyword if hiding was intended. // public event System.Action SP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP4").WithArguments("B.SP4", "A.SP4"), // (51,24): warning CS0108: 'B.IP1()' hides inherited member 'A.IP1'. Use the new keyword if hiding was intended. // public static void IP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP1").WithArguments("B.IP1()", "A.IP1"), // (52,17): warning CS0108: 'B.IP2()' hides inherited member 'A.IP2'. Use the new keyword if hiding was intended. // public void IP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP2").WithArguments("B.IP2()", "A.IP2"), // (53,39): warning CS0108: 'B.IP3' hides inherited member 'A.IP3'. Use the new keyword if hiding was intended. // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP3").WithArguments("B.IP3", "A.IP3"), // (54,32): warning CS0108: 'B.IP4' hides inherited member 'A.IP4'. Use the new keyword if hiding was intended. // public event System.Action IP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP4").WithArguments("B.IP4", "A.IP4"), // (56,24): warning CS0108: 'B.SE1()' hides inherited member 'A.SE1'. Use the new keyword if hiding was intended. // public static void SE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE1").WithArguments("B.SE1()", "A.SE1"), // (57,17): warning CS0108: 'B.SE2()' hides inherited member 'A.SE2'. Use the new keyword if hiding was intended. // public void SE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE2").WithArguments("B.SE2()", "A.SE2"), // (58,23): warning CS0108: 'B.SE3' hides inherited member 'A.SE3'. Use the new keyword if hiding was intended. // public static int SE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE3").WithArguments("B.SE3", "A.SE3"), // (59,16): warning CS0108: 'B.SE4' hides inherited member 'A.SE4'. Use the new keyword if hiding was intended. // public int SE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE4").WithArguments("B.SE4", "A.SE4"), // (61,24): warning CS0108: 'B.IE1()' hides inherited member 'A.IE1'. Use the new keyword if hiding was intended. // public static void IE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE1").WithArguments("B.IE1()", "A.IE1"), // (62,17): warning CS0108: 'B.IE2()' hides inherited member 'A.IE2'. Use the new keyword if hiding was intended. // public void IE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE2").WithArguments("B.IE2()", "A.IE2"), // (63,23): warning CS0108: 'B.IE3' hides inherited member 'A.IE3'. Use the new keyword if hiding was intended. // public static int IE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE3").WithArguments("B.IE3", "A.IE3"), // (64,16): warning CS0108: 'B.IE4' hides inherited member 'A.IE4'. Use the new keyword if hiding was intended. // public int IE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE4").WithArguments("B.IE4", "A.IE4"), // (53,39): warning CS0067: The event 'B.IP3' is never used // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IP3").WithArguments("B.IP3"), // (25,39): warning CS0067: The event 'A.SE2' is never used // public static event System.Action SE2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE2").WithArguments("A.SE2"), // (26,39): warning CS0067: The event 'A.SE3' is never used // public static event System.Action SE3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE3").WithArguments("A.SE3"), // (38,39): warning CS0067: The event 'B.SM3' is never used // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SM3").WithArguments("B.SM3"), // (279): warning CS0067: The event 'A.SE4' is never used // public static event System.Action SE4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE4").WithArguments("A.SE4"), // (48,39): warning CS0067: The event 'B.SP3' is never used // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SP3").WithArguments("B.SP3"), // (24,39): warning CS0067: The event 'A.SE1' is never used // public static event System.Action SE1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE1").WithArguments("A.SE1"), // (43,39): warning CS0067: The event 'B.IM3' is never used // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IM3").WithArguments("B.IM3")); } [WorkItem(539624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539624")] [Fact] public void CS0108WRN_NewRequired_Arity() { var text = @" class Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } class HideWithClass : Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public class M { } public class M<A> { } public class M<A, B> { } public class M<A, B, C> { } public class D { } public class D<A> { } public class D<A, B> { } public class D<A, B, C> { } } class HideWithMethod : Class { public void T() { } public void T<A>() { } public void T<A, B>() { } public void T<A, B, C>() { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public void D() { } public void D<A>() { } public void D<A, B>() { } public void D<A, B, C>() { } } class HideWithDelegate : Class { public delegate void T(); public delegate void T<A>(); public delegate void T<A, B>(); public delegate void T<A, B, C>(); public delegate void M(); public delegate void M<A>(); public delegate void M<A, B>(); public delegate void M<A, B, C>(); public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } "; CreateCompilation(text).VerifyDiagnostics( /* HideWithClass */ // (22,18): warning CS0108: 'HideWithClass.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T", "Class.T"), // (23,18): warning CS0108: 'HideWithClass.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A>", "Class.T<A>"), // (24,18): warning CS0108: 'HideWithClass.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B>", "Class.T<A, B>"), // (25,18): warning CS0108: 'HideWithClass.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B, C>", "Class.T<A, B, C>"), // (27,18): warning CS0108: 'HideWithClass.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M", "Class.M()"), // (28,18): warning CS0108: 'HideWithClass.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A>", "Class.M<A>()"), // (29,18): warning CS0108: 'HideWithClass.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B>", "Class.M<A, B>()"), // (30,18): warning CS0108: 'HideWithClass.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B, C>", "Class.M<A, B, C>()"), // (32,18): warning CS0108: 'HideWithClass.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D", "Class.D"), // (33,18): warning CS0108: 'HideWithClass.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A>", "Class.D<A>"), // (34,18): warning CS0108: 'HideWithClass.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B>", "Class.D<A, B>"), // (35,18): warning CS0108: 'HideWithClass.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B, C>", "Class.D<A, B, C>"), /* HideWithMethod */ // (40,17): warning CS0108: 'HideWithMethod.T()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T()", "Class.T"), // (41,17): warning CS0108: 'HideWithMethod.T<A>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A>()", "Class.T"), // (42,17): warning CS0108: 'HideWithMethod.T<A, B>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B>()", "Class.T"), // (43,17): warning CS0108: 'HideWithMethod.T<A, B, C>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B, C>()", "Class.T"), // (45,17): warning CS0108: 'HideWithMethod.M()' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M()", "Class.M()"), // (46,17): warning CS0108: 'HideWithMethod.M<A>()' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A>()", "Class.M<A>()"), // (47,17): warning CS0108: 'HideWithMethod.M<A, B>()' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B>()", "Class.M<A, B>()"), // (48,17): warning CS0108: 'HideWithMethod.M<A, B, C>()' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B, C>()", "Class.M<A, B, C>()"), // (50,17): warning CS0108: 'HideWithMethod.D()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D()", "Class.D"), // (51,17): warning CS0108: 'HideWithMethod.D<A>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A>()", "Class.D"), // (52,17): warning CS0108: 'HideWithMethod.D<A, B>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B>()", "Class.D"), // (53,17): warning CS0108: 'HideWithMethod.D<A, B, C>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B, C>()", "Class.D"), /* HideWithDelegate */ // (58,26): warning CS0108: 'HideWithDelegate.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T", "Class.T"), // (59,26): warning CS0108: 'HideWithDelegate.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A>", "Class.T<A>"), // (60,26): warning CS0108: 'HideWithDelegate.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B>", "Class.T<A, B>"), // (61,26): warning CS0108: 'HideWithDelegate.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B, C>", "Class.T<A, B, C>"), // (63,26): warning CS0108: 'HideWithDelegate.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M", "Class.M()"), // (64,26): warning CS0108: 'HideWithDelegate.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A>", "Class.M<A>()"), // (65,26): warning CS0108: 'HideWithDelegate.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B>", "Class.M<A, B>()"), // (66,26): warning CS0108: 'HideWithDelegate.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B, C>", "Class.M<A, B, C>()"), // (68,26): warning CS0108: 'HideWithDelegate.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D", "Class.D"), // (69,26): warning CS0108: 'HideWithDelegate.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A>", "Class.D<A>"), // (70,26): warning CS0108: 'HideWithDelegate.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B>", "Class.D<A, B>"), // (71,26): warning CS0108: 'HideWithDelegate.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B, C>", "Class.D<A, B, C>")); } [Fact, WorkItem(546736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546736")] public void CS0108WRN_NewRequired_Partial() { var text = @" partial class Parent { partial void PM(int x); private void M(int x) { } partial class Child : Parent { partial void PM(int x); private void M(int x) { } } } partial class AnotherChild : Parent { partial void PM(int x); private void M(int x) { } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_NewRequired, "PM").WithArguments("Parent.Child.PM(int)", "Parent.PM(int)"), Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Parent.Child.M(int)", "Parent.M(int)")); } [Fact] public void CS0109WRN_NewNotRequired() { var text = @"namespace x { public class a { public int i; } public class b : a { public new int i; public new int j; // CS0109 public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewNotRequired, Line = 11, Column = 24, IsWarning = true }); } [Fact] public void CS0114WRN_NewOrOverrideExpected() { var text = @"abstract public class clx { public abstract void f(); } public class cly : clx { public void f() // CS0114, hides base class member { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 8, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 14 } }); } [Fact] public void CS0282WRN_SequentialOnPartialClass() { var text = @" partial struct A { int i; } partial struct A { int j; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'A'. To specify an ordering, all instance fields must be in the same declaration. // partial struct A Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "A").WithArguments("A"), // (3,9): warning CS0169: The field 'A.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("A.i"), // (7,9): warning CS0169: The field 'A.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("A.j")); } [Fact] [WorkItem(23668, "https://github.com/dotnet/roslyn/issues/23668")] public void CS0282WRN_PartialWithPropertyButSingleField() { string program = @"partial struct X // No warning CS0282 { // The only field of X is a backing field of A. public int A { get; set; } } partial struct X : I { // This partial definition has no field. int I.A { get => A; set => A = value; } } interface I { int A { get; set; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics(); } /// <summary> /// import - Lib: class A { class B {} } /// vs. curr: Namespace A { class B {} } - use B /// </summary> [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS0435WRN_SameFullNameThisNsAgg01() { var text = @"namespace CSFields { public class FFF { } } namespace SA { class Test { CSFields.FFF var = null; void M(CSFields.FFF p) { } } } "; // class CSFields { class FFF {}} var ref1 = TestReferences.SymbolsTests.Fields.CSFields.dll; var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // void M(CSFields.FFF p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,9): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,22): warning CS0414: The field 'SA.Test.var' is assigned but its value is never used // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "var").WithArguments("SA.Test.var") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } /// <summary> /// import - Lib: class A {} vs. curr: class A { } /// </summary> [Fact] public void CS0436WRN_SameFullNameThisAggAgg01() { var text = @"class Class1 { } namespace SA { class Test { Class1 cls; void M(Class1 p) { } } } "; // Class1 var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // Roslyn gives CS1542 or CS0104 var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (8,16): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(Class1 p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,9): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Class1 cls; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,16): warning CS0169: The field 'SA.Test.cls' is never used // Class1 cls; Diagnostic(ErrorCode.WRN_UnreferencedField, "cls").WithArguments("SA.Test.cls")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(546077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546077")] public void MultipleSymbolDisambiguation() { var sourceRef1 = @" public class CCC { public class X { } } public class CNC { public class X { } } namespace NCC { public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } public class CNN { public class X { } } namespace NCN { public class X { } } namespace NNN { public class X { } } "; var sourceRef2 = @" public class CCC { public class X { } } namespace CNC { public class X { } } public class NCC{ public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } namespace CNN { public class X { } } public class NCN { public class X { } } namespace NNN { public class X { } } "; var sourceLib = @" public class CCC { public class X { } } namespace CCN { public class X { } } public class CNC { public class X { } } namespace CNN { public class X { } } public class NCC { public class X { } } namespace NCN { public class X { } } public class NNC { public class X { } } namespace NNN { public class X { } } internal class DC : CCC.X { } internal class DN : CCN.X { } internal class D3 : CNC.X { } internal class D4 : CNN.X { } internal class D5 : NCC.X { } internal class D6 : NCN.X { } internal class D7 : NNC.X { } internal class D8 : NNN.X { } "; var ref1 = CreateCompilation(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilation(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilation(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // In some cases we might order the symbols differently than Dev11 and thus reporting slightly different warnings. // E.g. (src:type, md:type, md:namespace) vs (src:type, md:namespace, md:type) // We report (type, type) ambiguity while Dev11 reports (type, namespace) ambiguity, but both are equally correct. // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. lib.VerifyDiagnostics( // C:\lib.cs(12,21): warning CS0435: The namespace 'CCN' in 'C:\lib.cs' conflicts with the imported type 'CCN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CCN").WithArguments(@"C:\lib.cs", "CCN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCN"), // C:\lib.cs(16,21): warning CS0435: The namespace 'NCN' in 'C:\lib.cs' conflicts with the imported type 'NCN' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "NCN").WithArguments(@"C:\lib.cs", "NCN", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN"), // C:\lib.cs(16,25): warning CS0436: The type 'NCN.X' in 'C:\lib.cs' conflicts with the imported type 'NCN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NCN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN.X"), // C:\lib.cs(11,21): warning CS0436: The type 'CCC' in 'C:\lib.cs' conflicts with the imported type 'CCC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CCC").WithArguments(@"C:\lib.cs", "CCC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCC"), // C:\lib.cs(15,21): warning CS0436: The type 'NCC' in 'C:\lib.cs' conflicts with the imported type 'NCC' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "NCC").WithArguments(@"C:\lib.cs", "NCC", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCC"), // C:\lib.cs(13,21): warning CS0436: The type 'CNC' in 'C:\lib.cs' conflicts with the imported type 'CNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CNC").WithArguments(@"C:\lib.cs", "CNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNC"), // C:\lib.cs(14,21): warning CS0435: The namespace 'CNN' in 'C:\lib.cs' conflicts with the imported type 'CNN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CNN").WithArguments(@"C:\lib.cs", "CNN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN"), // C:\lib.cs(14,25): warning CS0436: The type 'CNN.X' in 'C:\lib.cs' conflicts with the imported type 'CNN.X' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "CNN.X", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN.X"), // C:\lib.cs(17,21): warning CS0437: The type 'NNC' in 'C:\lib.cs' conflicts with the imported namespace 'NNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "NNC").WithArguments(@"C:\lib.cs", "NNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNC"), // C:\lib.cs(18,25): warning CS0436: The type 'NNN.X' in 'C:\lib.cs' conflicts with the imported type 'NNN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NNN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNN.X")); } [Fact] public void MultipleSourceSymbols1() { var sourceLib = @" public class C { } namespace C { } public class D : C { }"; // do not report lookup errors CreateCompilation(sourceLib).VerifyDiagnostics( // error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [Fact] public void MultipleSourceSymbols2() { var sourceRef1 = @" public class C { public class X { } } "; var sourceRef2 = @" namespace N { public class X { } } "; var sourceLib = @" public class C { public class X { } } namespace C { public class X { } } internal class D : C.X { } "; var ref1 = CreateCompilation(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilation(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilation(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // do not report lookup errors lib.VerifyDiagnostics( // C:\lib.cs(2,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [WorkItem(545725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545725")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg02() { var text = @" namespace System { class Int32 { const Int32 MaxValue = null; static void Main() { Int32 x = System.Int32.MaxValue; } } } "; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }).VerifyDiagnostics( // goo.cs(6,15): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,13): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,23): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "System.Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,19): warning CS0219: The variable 'x' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg03() { var text = @"namespace System { class Object { static void Main() { Console.WriteLine(""hello""); } } class Goo : object {} class Bar : Object {} }"; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }).VerifyDiagnostics( // goo.cs(11,17): warning CS0436: The type 'System.Object' in 'goo.cs' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("goo.cs", "System.Object", RuntimeCorLibName.FullName, "object")); } /// <summary> /// import- Lib: namespace A { class B{} } vs. curr: class A { class B {} } /// </summary> [Fact] public void CS0437WRN_SameFullNameThisAggNs01() { var text = @"public class AppCS { public class App { } } namespace SA { class Test { AppCS.App app = null; void M(AppCS.App p) { } } } "; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var cs00 = TestReferences.MetadataTests.NetModule01.ModuleCS00; var cs01 = TestReferences.MetadataTests.NetModule01.ModuleCS01; var vb01 = TestReferences.MetadataTests.NetModule01.ModuleVB01; var ref1 = TestReferences.MetadataTests.NetModule01.AppCS; // Roslyn CS1542 var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(AppCS.App p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,9): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // AppCS.App app = null; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,19): warning CS0414: The field 'SA.Test.app' is assigned but its value is never used // AppCS.App app = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "app").WithArguments("SA.Test.app")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [WorkItem(545649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545649")] [Fact] public void CS0437WRN_SameFullNameThisAggNs02() { var source = @" using System; class System { } "; // NOTE: both mscorlib.dll and System.Core.dll define types in the System namespace. var compilation = CreateCompilation( Parse(source, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", RuntimeCorLibName.FullName, "System"), // (2,7): error CS0138: A using namespace directive can only be applied to namespaces; 'System' is a type not a namespace // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [Fact] public void CS0465WRN_FinalizeMethod() { var text = @" class A { protected virtual void Finalize() {} // CS0465 } abstract class B { public abstract void Finalize(); // CS0465 } abstract class C { protected int Finalize() {return 0;} // No Warning protected abstract void Finalize(int x); // No Warning protected virtual void Finalize<T>() { } // No Warning } class D : C { protected override void Finalize(int x) { } // No Warning protected override void Finalize<U>() { } // No Warning }"; CreateCompilation(text).VerifyDiagnostics( // (4,27): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (9,25): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [Fact] public void CS0473WRN_ExplicitImplCollision() { var text = @"public interface ITest<T> { int TestMethod(int i); int TestMethod(T i); } public class ImplementingClass : ITest<int> { int ITest<int>.TestMethod(int i) // CS0473 { return i + 1; } public int TestMethod(int i) { return i - 1; } } class T { static int Main() { return 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 9, Column = 20, IsWarning = true }); } [Fact] public void CS0626WRN_ExternMethodNoImplementation01() { var source = @"class A : System.Attribute { } class B { extern void M(); extern object P1 { get; set; } extern static public bool operator !(B b); } class C { [A] extern void M(); [A] extern object P1 { get; set; } [A] extern static public bool operator !(C c); }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): warning CS0626: Method, operator, or accessor 'B.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("B.M()").WithLocation(4, 17), // (5,24): warning CS0626: Method, operator, or accessor 'B.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("B.P1.get").WithLocation(5, 24), // (5,29): warning CS0626: Method, operator, or accessor 'B.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("B.P1.set").WithLocation(5, 29), // (6,40): warning CS0626: Method, operator, or accessor 'B.operator !(B)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "!").WithArguments("B.operator !(B)").WithLocation(6, 40), // (11,28): warning CS0626: Method, operator, or accessor 'C.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P1.get").WithLocation(11, 28), // (11,33): warning CS0626: Method, operator, or accessor 'C.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("C.P1.set").WithLocation(11, 33)); } [WorkItem(544660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544660")] [WorkItem(530324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530324")] [Fact] public void CS0626WRN_ExternMethodNoImplementation02() { var source = @"class A : System.Attribute { } delegate void D(); class C { extern event D E1; [A] extern event D E2; }"; CreateCompilation(source).VerifyDiagnostics( // (5,20): warning CS0626: Method, operator, or accessor 'C.E1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event D E1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E1").WithArguments("C.E1.remove").WithLocation(5, 20), // (6,24): warning CS0626: Method, operator, or accessor 'C.E2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // [A] extern event D E2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E2").WithArguments("C.E2.remove").WithLocation(6, 24)); } [Fact] public void CS0628WRN_ProtectedInSealed01() { var text = @"namespace NS { sealed class Goo { protected int i = 0; protected internal void M() { } } sealed public class Bar<T> { internal protected void M1(T t) { } protected V M2<V>(T t) { return default(V); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 5, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 6, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 11, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 12, Column = 21, IsWarning = true }); } [Fact] public void CS0628WRN_ProtectedInSealed02() { var text = @"sealed class C { protected object P { get { return null; } } public int Q { get; protected set; } } sealed class C<T> { internal protected T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 3, Column = 22, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 4, Column = 35, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 45, IsWarning = true }); } [WorkItem(539588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539588")] [Fact] public void CS0628WRN_ProtectedInSealed03() { var text = @"abstract class C { protected abstract void M(); protected internal virtual int P { get { return 0; } } } sealed class D : C { protected override void M() { } protected internal override int P { get { return 0; } } protected void N() { } // CS0628 protected internal int Q { get { return 0; } } // CS0628 protected class Nested {} // CS0628 } "; CreateCompilation(text).VerifyDiagnostics( // (13,21): warning CS0628: 'D.Nested': new protected member declared in sealed class // protected class Nested {} // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Nested").WithArguments("D.Nested"), // (11,28): warning CS0628: 'D.Q': new protected member declared in sealed class // protected internal int Q { get { return 0; } } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Q").WithArguments("D.Q"), // (10,20): warning CS0628: 'D.N()': new protected member declared in sealed class // protected void N() { } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "N").WithArguments("D.N()") ); } [Fact] public void CS0628WRN_ProtectedInSealed04() { var text = @" sealed class C { protected event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (4,35): warning CS0628: 'C.E': new protected member declared in sealed class // protected event System.Action E; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "E").WithArguments("C.E"), // (4,35): warning CS0067: The event 'C.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0628WRN_ProtectedInSealed05() { const string text = @" abstract class C { protected C() { } } sealed class D : C { protected override D() { } protected D(byte b) { } protected internal D(short s) { } internal protected D(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,24): error CS0106: The modifier 'override' is not valid for this item // protected override D() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "D").WithArguments("override").WithLocation(9, 24), // (10,15): warning CS0628: 'D.D(byte)': new protected member declared in sealed class // protected D(byte b) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(byte)").WithLocation(10, 15), // (11,24): warning CS0628: 'D.D(short)': new protected member declared in sealed class // protected internal D(short s) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(short)").WithLocation(11, 24), // (12,24): warning CS0628: 'D.D(int)': new protected member declared in sealed class // internal protected D(int i) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(int)").WithLocation(12, 24)); } [Fact] public void CS0659WRN_EqualsWithoutGetHashCode() { var text = @"class Test { public override bool Equals(object o) { return true; } // CS0659 } // However the warning should NOT be produced if the Equals is not a 'real' override // of Equals. Neither of these should produce a warning: class Test2 { public new virtual bool Equals(object o) { return true; } } class Test3 : Test2 { public override bool Equals(object o) { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals() { var text = @" class TestBase { public new virtual bool Equals(object o) { return true; } } class Test : TestBase // CS0660 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } // This does not count! public override bool Equals(object o) { return true; } public override int GetHashCode() { return 0; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,7): warning CS0660: 'Test' defines operator == or operator != but does not override Object.Equals(object o) Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "Test").WithArguments("Test")); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals_NoWarningWhenOverriddenWithDynamicParameter() { string source = @" public class C { public override bool Equals(dynamic o) { return false; } public static bool operator ==(C v1, C v2) { return true; } public static bool operator !=(C v1, C v2) { return false; } public override int GetHashCode() { return base.GetHashCode(); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0661WRN_EqualityOpWithoutGetHashCode() { var text = @" class TestBase { // This does not count; it has to be overridden on Test. public override int GetHashCode() { return 123; } } class Test : TestBase // CS0661 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } public override bool Equals(object o) { return true; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test"), // (7,7): warning CS0661: 'Test' defines operator == or operator != but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact()] public void CS0672WRN_NonObsoleteOverridingObsolete() { var text = @"class MyClass { [System.Obsolete] public virtual void ObsoleteMethod() { } } class MyClass2 : MyClass { public override void ObsoleteMethod() // CS0672 { } } class MainClass { static public void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NonObsoleteOverridingObsolete, Line = 11, Column = 26, IsWarning = true }); } [Fact()] public void CS0684WRN_CoClassWithoutComImport() { var text = @" using System.Runtime.InteropServices; [CoClass(typeof(C))] // CS0684 interface I { } class C { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CoClassWithoutComImport, Line = 4, Column = 2, IsWarning = true }); } [Fact()] public void CS0809WRN_ObsoleteOverridingNonObsolete() { var text = @"public class Base { public virtual void Test1() { } } public class C : Base { [System.Obsolete()] public override void Test1() // CS0809 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ObsoleteOverridingNonObsolete, Line = 10, Column = 26, IsWarning = true }); } [Fact] public void CS0824WRN_ExternCtorNoImplementation01() { var source = @"namespace NS { public class C<T> { extern C(); struct S { extern S(string s); } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): warning CS0824: Constructor 'NS.C<T>.C()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("NS.C<T>.C()").WithLocation(5, 16), // (9,20): warning CS0824: Constructor 'NS.C<T>.S.S(string)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "S").WithArguments("NS.C<T>.S.S(string)").WithLocation(9, 20)); } [WorkItem(540859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540859")] [Fact] public void CS0824WRN_ExternCtorNoImplementation02() { var source = @"class A : System.Attribute { } class B { extern static B(); } class C { [A] extern static C(); }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): warning CS0824: Constructor 'B.B()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(4, 19)); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation03() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B(); } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(comp, verify: Verification.Skipped). VerifyDiagnostics( // (8,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(8, 17) ); var methods = verifier.TestData.GetMethodsByName().Keys; Assert.True(methods.Any(n => n.StartsWith("A..ctor", StringComparison.Ordinal))); Assert.False(methods.Any(n => n.StartsWith("B..ctor", StringComparison.Ordinal))); // Haven't tried to emit it } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation04() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation05() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(unknown); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(unknown); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation06() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(1) {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation07() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation08() { var source = @" public class B { private int x = 1; public extern B(); }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyEmitDiagnostics( // (5,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(5, 17), // (4,15): warning CS0414: The field 'B.x' is assigned but its value is never used // private int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("B.x").WithLocation(4, 15) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation09() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base(); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base(); // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation10() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base() {} // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation01() { // Slight change from the native compiler; in the native compiler the "int" gets the green squiggle. // This seems wrong; the error should either highlight the parameter "x" or the initializer " = 2". // I see no reason to highlight the "int". I've changed it to highlight the "x". var compilation = CreateCompilation( @"interface IFace { int Goo(int x = 1); } class B : IFace { int IFace.Goo(int x = 2) { return 0; } }"); compilation.VerifyDiagnostics( // (7,23): error CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithLocation(7, 23).WithArguments("x")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation02() { var compilation = CreateCompilation( @"interface I { object this[string index = null] { get; } //CS1066 object this[char c, char d] { get; } //CS1066 } class C : I { object I.this[string index = ""apple""] { get { return null; } } //CS1066 internal object this[int x, int y = 0] { get { return null; } } //fine object I.this[char c = 'c', char d = 'd'] { get { return null; } } //CS1066 x2 } "); compilation.VerifyDiagnostics( // (3,24): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (7,26): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (10,24): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (10,38): warning CS1066: The default value specified for parameter 'd' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "d").WithArguments("d")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation03() { var compilation = CreateCompilation( @" class C { public static C operator!(C c = null) { return c; } public static implicit operator int(C c = null) { return 0; } } "); compilation.VerifyDiagnostics( // (4,33): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static C operator!(C c = null) { return c; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (5,43): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static implicit operator int(C c = null) { return 0; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c") ); } // public void CS1698WRN_AssumedMatchThis() => Move to CommandLineTest [Fact] public void CS1699WRN_UseSwitchInsteadOfAttribute_RoslynWRN73() { var text = @" [assembly:System.Reflection.AssemblyDelaySign(true)] // CS1699 "; // warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'System.Reflection.AssemblyDelaySign' // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute, @"/delaysign").WithArguments(@"/delaysign", "System.Reflection.AssemblyDelaySign") // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given CreateCompilation(text).VerifyDiagnostics( // warning CS73: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); } [Fact(), WorkItem(544447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544447")] public void CS1700WRN_InvalidAssemblyName() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""' '"")] // ok [assembly: InternalsVisibleTo(""\t\r\n;a"")] // ok (whitespace escape) [assembly: InternalsVisibleTo(""\u1234;a"")] // ok (assembly name Unicode escape) [assembly: InternalsVisibleTo(""' a '"")] // ok [assembly: InternalsVisibleTo(""\u1000000;a"")] // invalid escape [assembly: InternalsVisibleTo(""a'b'c"")] // quotes in the middle [assembly: InternalsVisibleTo(""Test, PublicKey=Null"")] [assembly: InternalsVisibleTo(""Test, Bar"")] [assembly: InternalsVisibleTo(""Test, Version"")] [assembly: InternalsVisibleTo(""app2, Retargetable=f"")] // CS1700 "; // Tested against Dev12 CreateCompilation(text).VerifyDiagnostics( // (8,12): warning CS1700: Assembly reference 'a'b'c' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""a'b'c"")").WithArguments("a'b'c").WithLocation(8, 12), // (9,12): warning CS1700: Assembly reference 'Test, PublicKey=Null' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, PublicKey=Null"")").WithArguments("Test, PublicKey=Null").WithLocation(9, 12), // (10,12): warning CS1700: Assembly reference 'Test, Bar' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Bar"")").WithArguments("Test, Bar").WithLocation(10, 12), // (11,12): warning CS1700: Assembly reference 'Test, Version' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Version"")").WithArguments("Test, Version").WithLocation(11, 12), // (12,12): warning CS1700: Assembly reference 'app2, Retargetable=f' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""app2, Retargetable=f"")").WithArguments("app2, Retargetable=f").WithLocation(12, 12)); } // CS1701WRN_UnifyReferenceMajMin --> ReferenceManagerTests [Fact] public void CS1956WRN_MultipleRuntimeImplementationMatches() { var text = @"class Base<T, S> { public virtual int Test(out T x) // CS1956 { x = default(T); return 0; } public virtual int Test(ref S x) { return 1; } } interface IFace { int Test(out int x); } class Derived : Base<int, int>, IFace { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeImplementationMatches, Line = 20, Column = 33, IsWarning = true }); } [Fact] public void CS1957WRN_MultipleRuntimeOverrideMatches() { var text = @"class Base<TString> { public virtual void Test(TString s, out int x) { x = 0; } public virtual void Test(string s, ref int x) { } // CS1957 } class Derived : Base<string> { public override void Test(string s, ref int x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeOverrideMatches, Line = 8, Column = 25, IsWarning = true }); } [Fact] public void CS3000WRN_CLS_NoVarArgs() { var text = @" [assembly: System.CLSCompliant(true)] public class Test { public void AddABunchOfInts( __arglist) { } // CS3000 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): warning CS3000: Methods with variable arguments are not CLS-compliant // public void AddABunchOfInts( __arglist) { } // CS3000 Diagnostic(ErrorCode.WRN_CLS_NoVarArgs, "AddABunchOfInts")); } [Fact] public void CS3001WRN_CLS_BadArgType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public void bad(ushort i) // CS3001 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,28): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void bad(ushort i) // CS3001 Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i").WithArguments("ushort")); } [Fact] public void CS3002WRN_CLS_BadReturnType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort bad() // CS3002, public method { return ushort.MaxValue; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,19): warning CS3002: Return type of 'a.bad()' is not CLS-compliant // public ushort bad() // CS3002, public method Diagnostic(ErrorCode.WRN_CLS_BadReturnType, "bad").WithArguments("a.bad()")); } [Fact] public void CS3003WRN_CLS_BadFieldPropType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort a1; // CS3003, public variable public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,19): warning CS3003: Type of 'a.a1' is not CLS-compliant // public ushort a1; // CS3003, public variable Diagnostic(ErrorCode.WRN_CLS_BadFieldPropType, "a1").WithArguments("a.a1")); } [Fact] public void CS3005WRN_CLS_BadIdentifierCase() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int a1 = 0; public static int A1 = 1; // CS3005 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,23): warning CS3005: Identifier 'a.A1' differing only in case is not CLS-compliant // public static int A1 = 1; // CS3005 Diagnostic(ErrorCode.WRN_CLS_BadIdentifierCase, "A1").WithArguments("a.A1")); } [Fact] public void CS3006WRN_CLS_OverloadRefOut() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyClass { public void f(int i) { } public void f(ref int i) // CS3006 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): warning CS3006: Overloaded method 'MyClass.f(ref int)' differing only in ref or out, or in array rank, is not CLS-compliant // public void f(ref int i) // CS3006 Diagnostic(ErrorCode.WRN_CLS_OverloadRefOut, "f").WithArguments("MyClass.f(ref int)")); } [Fact] public void CS3007WRN_CLS_OverloadUnnamed() { var text = @"[assembly: System.CLSCompliant(true)] public struct S { public void F(int[][] array) { } public void F(byte[][] array) { } // CS3007 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): warning CS3007: Overloaded method 'S.F(byte[][])' differing only by unnamed array types is not CLS-compliant // public void F(byte[][] array) { } // CS3007 Diagnostic(ErrorCode.WRN_CLS_OverloadUnnamed, "F").WithArguments("S.F(byte[][])")); } [Fact] public void CS3008WRN_CLS_BadIdentifier() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int _a = 0; // CS3008 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,23): warning CS3008: Identifier '_a' is not CLS-compliant // public static int _a = 0; // CS3008 Diagnostic(ErrorCode.WRN_CLS_BadIdentifier, "_a").WithArguments("_a")); } [Fact] public void CS3009WRN_CLS_BadBase() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class B { } public class C : B // CS3009 { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,14): warning CS3009: 'C': base type 'B' is not CLS-compliant // public class C : B // CS3009 Diagnostic(ErrorCode.WRN_CLS_BadBase, "C").WithArguments("C", "B")); } [Fact] public void CS3010WRN_CLS_BadInterfaceMember() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I { [CLSCompliant(false)] int M(); // CS3010 } public class C : I { public int M() { return 1; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): warning CS3010: 'I.M()': CLS-compliant interfaces must have only CLS-compliant members // int M(); // CS3010 Diagnostic(ErrorCode.WRN_CLS_BadInterfaceMember, "M").WithArguments("I.M()")); } [Fact] public void CS3011WRN_CLS_NoAbstractMembers() { var text = @"using System; [assembly: CLSCompliant(true)] public abstract class I { [CLSCompliant(false)] public abstract int M(); // CS3011 } public class C : I { public override int M() { return 1; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,25): warning CS3011: 'I.M()': only CLS-compliant members can be abstract // public abstract int M(); // CS3011 Diagnostic(ErrorCode.WRN_CLS_NoAbstractMembers, "M").WithArguments("I.M()")); } [Fact] public void CS3012WRN_CLS_NotOnModules() { var text = @"[module: System.CLSCompliant(true)] // CS3012 public class C { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (1,10): warning CS3012: You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking // [module: System.CLSCompliant(true)] // CS3012 Diagnostic(ErrorCode.WRN_CLS_NotOnModules, "System.CLSCompliant(true)")); } [Fact] public void CS3013WRN_CLS_ModuleMissingCLS() { var netModule = CreateEmptyCompilation("", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(expectedWarnings: new[] { Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion) }); CreateCompilation("[assembly: System.CLSCompliant(true)]", new[] { netModule }).VerifyDiagnostics( // lib.netmodule: warning CS3013: Added modules must be marked with the CLSCompliant attribute to match the assembly Diagnostic(ErrorCode.WRN_CLS_ModuleMissingCLS)); } [Fact] public void CS3014WRN_CLS_AssemblyNotCLS() { var text = @"using System; // [assembly:CLSCompliant(true)] public class I { [CLSCompliant(true)] // CS3014 public void M() { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): warning CS3014: 'I.M()' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute // public void M() Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS, "M").WithArguments("I.M()")); } [Fact] public void CS3015WRN_CLS_BadAttributeType() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyAttribute : Attribute { public MyAttribute(int[] ai) { } // CS3015 } "; CreateCompilation(text).VerifyDiagnostics( // (4,14): warning CS3015: 'MyAttribute' has no accessible constructors which use only CLS-compliant types // public class MyAttribute : Attribute Diagnostic(ErrorCode.WRN_CLS_BadAttributeType, "MyAttribute").WithArguments("MyAttribute")); } [Fact] public void CS3016WRN_CLS_ArrayArgumentToAttribute() { var text = @"using System; [assembly: CLSCompliant(true)] [C(new int[] { 1, 2 })] // CS3016 public class C : Attribute { public C() { } public C(int[] a) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,2): warning CS3016: Arrays as attribute arguments is not CLS-compliant // [C(new int[] { 1, 2 })] // CS3016 Diagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, "C(new int[] { 1, 2 })")); } [Fact] public void CS3017WRN_CLS_NotOnModules2() { var text = @"using System; [module: CLSCompliant(true)] [assembly: CLSCompliant(false)] // CS3017 class C { static void Main() { } } "; // NOTE: unlike dev11, roslyn assumes that [assembly:CLSCompliant(false)] means // "suppress all CLS diagnostics". CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS3018WRN_CLS_IllegalTrueInFalse() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class Outer { [CLSCompliant(true)] // CS3018 public class Nested { } [CLSCompliant(false)] public class Nested3 { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): warning CS3018: 'Outer.Nested' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type 'Outer' // public class Nested { } Diagnostic(ErrorCode.WRN_CLS_IllegalTrueInFalse, "Nested").WithArguments("Outer.Nested", "Outer")); } [Fact] public void CS3019WRN_CLS_MeaninglessOnPrivateType() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] // CS3019 class C { [CLSCompliant(false)] // CS3019 void Test() { } static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,7): warning CS3019: CLS compliance checking will not be performed on 'C' because it is not visible from outside this assembly // class C Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "C").WithArguments("C"), // (7,10): warning CS3019: CLS compliance checking will not be performed on 'C.Test()' because it is not visible from outside this assembly // void Test() Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "Test").WithArguments("C.Test()")); } [Fact] public void CS3021WRN_CLS_AssemblyNotCLS2() { var text = @"using System; [CLSCompliant(false)] // CS3021 public class C { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,14): warning CS3021: 'C' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute // public class C Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS2, "C").WithArguments("C")); } [Fact] public void CS3022WRN_CLS_MeaninglessOnParam() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] public class C { public void F([CLSCompliant(true)] int i) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,20): warning CS3022: CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead. // public void F([CLSCompliant(true)] int i) Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnParam, "CLSCompliant(true)")); } [Fact] public void CS3023WRN_CLS_MeaninglessOnReturn() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { [return: System.CLSCompliant(true)] // CS3023 public static int Main() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,14): warning CS3023: CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead. // [return: System.CLSCompliant(true)] // CS3023 Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnReturn, "System.CLSCompliant(true)")); } [Fact] public void CS3024WRN_CLS_BadTypeVar() { var text = @"[assembly: System.CLSCompliant(true)] [type: System.CLSCompliant(false)] public class TestClass // CS3024 { public ushort us; } [type: System.CLSCompliant(false)] public interface ITest // CS3024 { } public interface I<T> where T : TestClass { } public class TestClass_2<T> where T : ITest { } public class TestClass_3<T> : I<T> where T : TestClass { } public class TestClass_4<T> : TestClass_2<T> where T : ITest { } public class Test { public static int Main() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,20): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public interface I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass"), // (13,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (17,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_4<T> : TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (15,26): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public class TestClass_3<T> : I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass")); } [Fact] public void CS3026WRN_CLS_VolatileField() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { public volatile int v0 = 0; // CS3026 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_VolatileField, Line = 4, Column = 25, IsWarning = true }); } [Fact] public void CS3027WRN_CLS_BadInterface() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I1 { } [CLSCompliant(false)] public interface I2 { } public interface I : I1, I2 { } public class Goo { static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_BadInterface, Line = 13, Column = 18, IsWarning = true }); } #endregion #region "Regressions or Mixed errors" [Fact] // bug 1985 public void ConstructWithErrors() { var text = @" class Base<T>{} class Derived : Base<NotFound>{}"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 22 }); var derived = comp.SourceModule.GlobalNamespace.GetTypeMembers("Derived").Single(); var Base = derived.BaseType(); Assert.Equal(TypeKind.Class, Base.TypeKind); } [Fact] // bug 3045 public void AliasQualifiedName00() { var text = @"using NSA = A; namespace A { class Goo { } } namespace B { class Test { class NSA { public NSA(int Goo) { this.Goo = Goo; } int Goo; } static int Main() { NSA::Goo goo = new NSA::Goo(); // shouldn't error here goo = Xyzzy; return 0; } static NSA::Goo Xyzzy = null; // shouldn't error here } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; var test = b.GetMembers("Test").Single() as NamedTypeSymbol; var nsa = test.GetMembers("NSA").Single() as NamedTypeSymbol; Assert.Equal(2, nsa.GetMembers().Length); } [WorkItem(538218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538218")] [Fact] public void RecursiveInterfaceLookup01() { var text = @"interface A<T> { } interface B : A<B.Garbage> { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DottedTypeNameNotFoundInAgg, Line = 2, Column = 19 }); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; } [WorkItem(538150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538150")] [Fact] public void CS0102ERR_DuplicateNameInClass04() { var text = @" namespace NS { struct MyType { public class MyMeth { } public void MyMeth() { } public int MyMeth; } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public void MyMeth() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public int MyMeth; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): warning CS0649: Field 'NS.MyType.MyMeth' is never assigned to, and will always have its default value 0 // public int MyMeth; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "MyMeth").WithArguments("NS.MyType.MyMeth", "0") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("MyType").Single() as NamedTypeSymbol; Assert.Equal(4, type1.GetMembers().Length); // constructor included } [Fact] public void CS0102ERR_DuplicateNameInClass05() { CreateCompilation( @"class C { void P() { } int P { get { return 0; } } object Q { get; set; } void Q(int x, int y) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 9), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 10)); } [Fact] public void CS0102ERR_DuplicateNameInClass06() { CreateCompilation( @"class C { private double get_P; // CS0102 private int set_P { get { return 0; } } // CS0102 void get_Q(object o) { } // no error class set_Q { } // CS0102 public int P { get; set; } object Q { get { return null; } } object R { set { } } enum get_R { } // CS0102 struct set_R { } // CS0102 }") .VerifyDiagnostics( // (7,20): error CS0102: The type 'C' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C", "get_P"), // (7,25): error CS0102: The type 'C' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_P"), // (8,12): error CS0102: The type 'C' already contains a definition for 'set_Q' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "set_Q"), // (9,12): error CS0102: The type 'C' already contains a definition for 'get_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "R").WithArguments("C", "get_R"), // (9,16): error CS0102: The type 'C' already contains a definition for 'set_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_R"), // (3,20): warning CS0169: The field 'C.get_P' is never used // private double get_P; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("C.get_P")); } [Fact] public void CS0102ERR_DuplicateNameInClass07() { CreateCompilation( @"class C { public int P { get { return 0; } set { } } public bool P { get { return false; } } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(8, 17)); } [WorkItem(538616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538616")] [Fact] public void CS0102ERR_DuplicateNameInClass08() { var text = @" class A<T> { void T() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 10 }); } [WorkItem(538917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538917")] [Fact] public void CS0102ERR_DuplicateNameInClass09() { var text = @" class A<T> { class T<S> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 11 }); } [WorkItem(538634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538634")] [Fact] public void CS0102ERR_DuplicateNameInClass10() { var text = @"class C<A, B, D, E, F, G> { object A; void B() { } object D { get; set; } class E { } struct F { } enum G { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'A' // object A; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "A").WithArguments("C<A, B, D, E, F, G>", "A"), // (4,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'B' // void B() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "B").WithArguments("C<A, B, D, E, F, G>", "B"), // (5,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'D' // object D { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C<A, B, D, E, F, G>", "D"), // (6,11): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'E' // class E { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C<A, B, D, E, F, G>", "E"), // (7,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'F' // struct F { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C<A, B, D, E, F, G>", "F"), // (8,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'G' // enum G { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C<A, B, D, E, F, G>", "G"), // (3,12): warning CS0169: The field 'C<A, B, D, E, F, G>.A' is never used // object A; Diagnostic(ErrorCode.WRN_UnreferencedField, "A").WithArguments("C<A, B, D, E, F, G>.A")); } [Fact] public void CS0101ERR_DuplicateNameInNS05() { CreateCompilation( @"namespace N { enum E { A, B } enum E { A } // CS0101 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "E").WithArguments("E", "N").WithLocation(4, 10)); } [WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")] [Fact] public void CS0101ERR_DuplicateNameInNS06() { CreateCompilation( @"namespace N { interface I { int P { get; } object Q { get; } } interface I // CS0101 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0101 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0101 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0101: The namespace 'N' already contains a definition for 'I' // interface I // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "I").WithArguments("I", "N"), // (17,12): error CS0101: The namespace 'N' already contains a definition for 'S' // struct S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (22,11): error CS0101: The namespace 'N' already contains a definition for 'S' // class S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (27,18): error CS0101: The namespace 'N' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "D").WithArguments("D", "N"), // (24,16): warning CS0169: The field 'N.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("N.S.T"), // (20,13): warning CS0169: The field 'N.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("N.S.I") ); } [WorkItem(539742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539742")] [Fact] public void CS0102ERR_DuplicateNameInClass11() { CreateCompilation( @"class C { enum E { A, B } enum E { A } // CS0102 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "E").WithLocation(4, 10)); } [WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")] [Fact] public void CS0102ERR_DuplicateNameInClass12() { CreateCompilation( @"class C { interface I { int P { get; } object Q { get; } } interface I // CS0102 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0102 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0102 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0102: The type 'C' already contains a definition for 'I' // interface I // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("C", "I"), // (17,12): error CS0102: The type 'C' already contains a definition for 'S' // struct S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (22,11): error CS0102: The type 'C' already contains a definition for 'S' // class S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (27,18): error CS0102: The type 'C' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C", "D"), // (24,16): warning CS0169: The field 'C.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("C.S.T"), // (20,13): warning CS0169: The field 'C.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("C.S.I") ); } [Fact] public void CS0102ERR_DuplicateNameInClass13() { CreateCompilation( @"class C { private double add_E; // CS0102 private event System.Action remove_E; // CS0102 void add_F(object o) { } // no error class remove_F { } // CS0102 public event System.Action E; event System.Action F; event System.Action G; enum add_G { } // CS0102 struct remove_G { } // CS0102 }") .VerifyDiagnostics( // (72): error CS0102: The type 'C' already contains a definition for 'add_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "add_E"), // (72): error CS0102: The type 'C' already contains a definition for 'remove_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "remove_E"), // (8,25): error CS0102: The type 'C' already contains a definition for 'remove_F' // event System.Action F; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C", "remove_F"), // (9,25): error CS0102: The type 'C' already contains a definition for 'add_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "add_G"), // (9,25): error CS0102: The type 'C' already contains a definition for 'remove_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "remove_G"), // (8,25): warning CS0067: The event 'C.F' is never used // event System.Action F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("C.F"), // (3,20): warning CS0169: The field 'C.add_E' is never used // private double add_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "add_E").WithArguments("C.add_E"), // (4,33): warning CS0067: The event 'C.remove_E' is never used // private event System.Action remove_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "remove_E").WithArguments("C.remove_E"), // (72): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E"), // (9,25): warning CS0067: The event 'C.G' is never used // event System.Action G; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "G").WithArguments("C.G")); } [Fact] public void CS0102ERR_DuplicateNameInClass14() { var text = @"using System.Runtime.CompilerServices; interface I { object this[object index] { get; set; } void Item(); } struct S { [IndexerName(""P"")] object this[object index] { get { return null; } } object Item; // no error object P; } class A { object get_Item; object set_Item; object this[int x, int y] { set { } } } class B { [IndexerName(""P"")] object this[object index] { get { return null; } } object get_Item; // no error object get_P; } class A1 { internal object this[object index] { get { return null; } } } class A2 { internal object Item; // no error } class B1 : A1 { internal object Item; } class B2 : A2 { internal object this[object index] { get { return null; } } // no error }"; CreateCompilation(text).VerifyDiagnostics( // (4,12): error CS0102: The type 'I' already contains a definition for 'Item' // object this[object index] { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("I", "Item"), // (10,12): error CS0102: The type 'S' already contains a definition for 'P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("S", "P"), // (18,12): error CS0102: The type 'A' already contains a definition for 'get_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (18,33): error CS0102: The type 'A' already contains a definition for 'set_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (23,33): error CS0102: The type 'B' already contains a definition for 'get_P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("B", "get_P"), // (11,12): warning CS0169: The field 'S.Item' is never used // object Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("S.Item"), // (12,12): warning CS0169: The field 'S.P' is never used // object P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("S.P"), // (16,12): warning CS0169: The field 'A.get_Item' is never used // object get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item"), // (17,12): warning CS0169: The field 'A.set_Item' is never used // object set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item"), // (24,12): warning CS0169: The field 'B.get_Item' is never used // object get_Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("B.get_Item"), // (25,12): warning CS0169: The field 'B.get_P' is never used // object get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("B.get_P"), // (33,21): warning CS0649: Field 'A2.Item' is never assigned to, and will always have its default value null // internal object Item; // no error Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("A2.Item", "null"), // (37,21): warning CS0649: Field 'B1.Item' is never assigned to, and will always have its default value null // internal object Item; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("B1.Item", "null") ); } // Indexers without IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass15() { var template = @" class A {{ public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilation(string.Format(template, "int Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item"), // (5,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); // Error even though the indexer doesn't have a getter CreateCompilation(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (5,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilation(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (5,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); // Error even though the signatures don't match CreateCompilation(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item")); // Since the signatures don't match CreateCompilation(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } // Indexers with IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass16() { var template = @" using System.Runtime.CompilerServices; class A {{ [IndexerName(""P"")] public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilation(string.Format(template, "int P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P"), // (7,9): warning CS0169: The field 'A.P' is never used // int P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("A.P")); // Error even though the indexer doesn't have a getter CreateCompilation(string.Format(template, "int get_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_P"), // (7,9): warning CS0169: The field 'A.get_P' is never used // int get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("A.get_P")); CreateCompilation(string.Format(template, "int set_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_P"), // (7,9): warning CS0169: The field 'A.set_P' is never used // int set_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_P").WithArguments("A.set_P")); // Error even though the signatures don't match CreateCompilation(string.Format(template, "int P() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P")); // Since the signatures don't match CreateCompilation(string.Format(template, "int set_P() { return 0; }")).VerifyDiagnostics(); // No longer have issues with "Item" names CreateCompilation(string.Format(template, "int Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); CreateCompilation(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilation(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); CreateCompilation(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics(); CreateCompilation(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } [WorkItem(539625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539625")] [Fact] public void CS0104ERR_AmbigContext02() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I<string>.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I<A1> { public static int Method() { return 1; } } namespace LevelThree { public class I<A1> { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [Fact] public void CS0104ERR_AmbigContext03() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I { public static int Method() { return 1; } } namespace LevelThree { public class I { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [WorkItem(540255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540255")] [Fact] public void CS0122ERR_BadAccess01() { var text = @" interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Goo(new A.C()); } static void Goo<T>(I<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 15, Column = 9 }); } [Fact] public void CS0122ERR_BadAccess02() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Goo(new A.C()); } static void Goo<T>(I<T> x) { } static void Goo<T>(J<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); // no errors } [Fact] public void CS0122ERR_BadAccess03() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { System.Console.WriteLine(""I""); } // static void M<T>(J<T> c) // { // System.Console.WriteLine(""J""); // } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 29, Column = 15 }); } [Fact] public void CS0122ERR_BadAccess04() { var text = @"using System; interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void M<T>(J<T> c) { Console.WriteLine(""J""); } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(3202, "DevDiv_Projects/Roslyn")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_InaccessibleImport() { var text = @"using A = A; namespace X { using B; } static class A { private static class B { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,11): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // using B; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(4, 11), // (1,1): info CS8019: Unnecessary using directive. // using A = A; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = A;").WithLocation(1, 1), // (4,5): info CS8019: Unnecessary using directive. // using B; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using B;").WithLocation(4, 5)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_1() { var text = @"class ClassA { object F = new { f1<int> = 1 }; public static int f1 { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,22): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. // object F = new { f1<int> = 1 }; Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "f1<int> = 1").WithLocation(3, 22), // (3,22): error CS0307: The property 'ClassA.f1' cannot be used with type arguments // object F = new { f1<int> = 1 }; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f1<int>").WithArguments("ClassA.f1", "property").WithLocation(3, 22)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_2() { var text = @"class ClassA { object F = new { f1<T> }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_TypeArgsNotAllowed, Line = 3, Column = 22 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_3() { var text = @"class ClassA { object F = new { f1+ }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidExprTerm, Line = 3, Column = 26 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_4() { var text = @"class ClassA { object F = new { f1<int> }; public static int f1<T>() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,22): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. // object F = new { f1<int> }; Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "f1<int>").WithLocation(3, 22), // (3,22): error CS0828: Cannot assign method group to anonymous type property // object F = new { f1<int> }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "f1<int>").WithArguments("method group").WithLocation(3, 22)); } [Fact] public void CS7025ERR_BadVisEventType() { var text = @"internal interface InternalInterface { } internal delegate void InternalDelegate(); public class PublicClass { protected class Protected { } public event System.Action<InternalInterface> A; public event System.Action<InternalClass> B; internal event System.Action<Protected> C; public event InternalDelegate D; public event InternalDelegate E { add { } remove { } } } internal class InternalClass : PublicClass { public event System.Action<Protected> F; } "; CreateCompilation(text).VerifyDiagnostics( // (9,51): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalInterface>' is less accessible than event 'PublicClass.A' // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.ERR_BadVisEventType, "A").WithArguments("PublicClass.A", "System.Action<InternalInterface>"), // (10,47): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalClass>' is less accessible than event 'PublicClass.B' // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.ERR_BadVisEventType, "B").WithArguments("PublicClass.B", "System.Action<InternalClass>"), // (11,45): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'PublicClass.C' // internal event System.Action<Protected> C; Diagnostic(ErrorCode.ERR_BadVisEventType, "C").WithArguments("PublicClass.C", "System.Action<PublicClass.Protected>"), // (13,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.D' // public event InternalDelegate D; Diagnostic(ErrorCode.ERR_BadVisEventType, "D").WithArguments("PublicClass.D", "InternalDelegate"), // (14,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.E' // public event InternalDelegate E { add { } remove { } } Diagnostic(ErrorCode.ERR_BadVisEventType, "E").WithArguments("PublicClass.E", "InternalDelegate"), // (18,43): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'InternalClass.F' // public event System.Action<Protected> F; Diagnostic(ErrorCode.ERR_BadVisEventType, "F").WithArguments("InternalClass.F", "System.Action<PublicClass.Protected>"), // (9,51): warning CS0067: The event 'PublicClass.A' is never used // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "A").WithArguments("PublicClass.A"), // (10,47): warning CS0067: The event 'PublicClass.B' is never used // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("PublicClass.B"), // (11,45): warning CS0067: The event 'PublicClass.C' is never used // internal event System.Action<Protected> C; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "C").WithArguments("PublicClass.C"), // (13,35): warning CS0067: The event 'PublicClass.D' is never used // public event InternalDelegate D; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "D").WithArguments("PublicClass.D"), // (18,43): warning CS0067: The event 'InternalClass.F' is never used // public event System.Action<Protected> F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("InternalClass.F")); } [Fact, WorkItem(543386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543386")] public void VolatileFieldWithGenericTypeConstrainedToClass() { var text = @" public class C {} class G<T> where T : C { public volatile T Fld = default(T); } "; CreateCompilation(text).VerifyDiagnostics(); } #endregion [WorkItem(7920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7920")] [Fact()] public void Bug7920() { var comp1 = CreateCompilation(@" public class MyAttribute1 : System.Attribute {} ", options: TestOptions.ReleaseDll, assemblyName: "Bug7920_CS"); var comp2 = CreateCompilation(@" public class MyAttribute2 : MyAttribute1 {} ", new[] { new CSharpCompilationReference(comp1) }, options: TestOptions.ReleaseDll); var expected = new[] { // (2,2): error CS0012: The type 'MyAttribute1' is defined in an assembly that is not referenced. You must add a reference to assembly 'Bug7920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [MyAttribute2] Diagnostic(ErrorCode.ERR_NoTypeDef, "MyAttribute2").WithArguments("MyAttribute1", "Bug7920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") }; var source3 = @" [MyAttribute2] public class Test {} "; var comp3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseDll); comp3.GetDiagnostics().Verify(expected); var comp4 = CreateCompilation(source3, new[] { comp2.EmitToImageReference() }, options: TestOptions.ReleaseDll); comp4.GetDiagnostics().Verify(expected); } [Fact, WorkItem(345, "https://github.com/dotnet/roslyn")] public void InferredStaticTypeArgument() { var source = @"class Program { static void Main(string[] args) { M(default(C)); } public static void M<T>(T t) { } } static class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0718: 'C': static types cannot be used as type arguments // M(default(C)); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "M").WithArguments("C").WithLocation(5, 9) ); } [Fact, WorkItem(511, "https://github.com/dotnet/roslyn")] public void StaticTypeArgumentOfDynamicInvocation() { var source = @"static class S {} class C { static void M() { dynamic d1 = 123; d1.N<S>(); // The dev11 compiler does not diagnose this } static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AbstractInScript() { var source = @"internal abstract void M(); internal abstract object P { get; } internal abstract event System.EventHandler E;"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (1,24): error CS0513: 'M()' is abstract but it is contained in non-abstract class 'Script' // internal abstract void M(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("M()", "Script").WithLocation(1, 24), // (2,30): error CS0513: 'P.get' is abstract but it is contained in non-abstract class 'Script' // internal abstract object P { get; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("P.get", "Script").WithLocation(2, 30), // (3,45): error CS0513: 'E' is abstract but it is contained in non-abstract class 'Script' // internal abstract event System.EventHandler E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("E", "Script").WithLocation(3, 45)); } [WorkItem(529225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529225")] [Fact] public void AbstractInSubmission() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source = @"internal abstract void M(); internal abstract object P { get; } internal abstract event System.EventHandler E;"; var submission = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Script), new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }); submission.VerifyDiagnostics( // (1,24): error CS0513: 'M()' is abstract but it is contained in non-abstract class 'Script' // internal abstract void M(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("M()", "Script").WithLocation(1, 24), // (2,30): error CS0513: 'P.get' is abstract but it is contained in non-abstract class 'Script' // internal abstract object P { get; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("P.get", "Script").WithLocation(2, 30), // (3,45): error CS0513: 'E' is abstract but it is contained in non-abstract class 'Script' // internal abstract event System.EventHandler E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("E", "Script").WithLocation(3, 45)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsOfATypeToDifferentAssembliesWithoutUsingItShouldNotReportAnError() { var forwardingIL = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly Forwarding { } .module Forwarding.dll .assembly extern Destination1 { } .assembly extern Destination2 { } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 } .class public auto ansi beforefieldinit TestSpace.ExistingReference extends [mscorlib]System.Object { .field public static literal string Value = ""TEST VALUE"" .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: nop IL_0007: ret } }"; var ilReference = CompileIL(forwardingIL, prependDefaultHeader: false); var code = @" using TestSpace; namespace UserSpace { public class Program { public static void Main() { System.Console.WriteLine(ExistingReference.Value); } } }"; CompileAndVerify( source: code, references: new MetadataReference[] { ilReference }, expectedOutput: "TEST VALUE"); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsOfFullyQualifiedTypeToDifferentAssembliesWhileReferencingItShouldErrorOut() { var userCode = @" namespace ForwardingNamespace { public class Program { public static void Main() { new Destination.TestClass(); } } }"; var forwardingIL = @" .assembly extern Destination1 { .ver 1:0:0:0 } .assembly extern Destination2 { .ver 1:0:0:0 } .assembly Forwarder { .ver 1:0:0:0 } .module ForwarderModule.dll .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 }"; var compilation = CreateCompilationWithILAndMscorlib40(userCode, forwardingIL, appendDefaultHeader: false); compilation.VerifyDiagnostics( // (8,29): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestClass").WithArguments("ForwarderModule.dll", "Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination.TestClass", "Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 29), // (8,29): error CS0234: The type or namespace name 'TestClass' does not exist in the namespace 'Destination' (are you missing an assembly reference?) // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestClass").WithArguments("TestClass", "Destination").WithLocation(8, 29)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsToManyAssembliesShouldJustReportTheFirstTwo() { var userCode = @" namespace ForwardingNamespace { public class Program { public static void Main() { new Destination.TestClass(); } } }"; var forwardingIL = @" .assembly Forwarder { } .module ForwarderModule.dll .assembly extern Destination1 { } .assembly extern Destination2 { } .assembly extern Destination3 { } .assembly extern Destination4 { } .assembly extern Destination5 { } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 } .class extern forwarder Destination.TestClass { .assembly extern Destination3 } .class extern forwarder Destination.TestClass { .assembly extern Destination4 } .class extern forwarder Destination.TestClass { .assembly extern Destination5 } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 }"; var compilation = CreateCompilationWithILAndMscorlib40(userCode, forwardingIL, appendDefaultHeader: false); compilation.VerifyDiagnostics( // (8,29): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestClass").WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination.TestClass", "Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 29), // (8,29): error CS0234: The type or namespace name 'TestClass' does not exist in the namespace 'Destination' (are you missing an assembly reference?) // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestClass").WithArguments("TestClass", "Destination").WithLocation(8, 29)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void RequiredExternalTypesForAMethodSignatureWillReportErrorsIfForwardedToMultipleAssemblies() { // The scenario is that assembly A is calling a method from assembly B. This method has a parameter of a type that lives // in assembly C. If A is compiled against B and C, it should compile successfully. // Now if assembly C is replaced with assembly C2, that forwards the type to both D1 and D2, it should fail with the appropriate error. var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static void MethodB(ClassC obj) { System.Console.WriteLine(obj.GetHashCode()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeA = @" using B; namespace A { public class ClassA { public void MethodA() { ClassB.MethodB(null); } } }"; CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC }, assemblyName: "A").VerifyDiagnostics(); // No Errors var codeC2 = @" .assembly C { } .module CModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder C.ClassC { .assembly extern D1 } .class extern forwarder C.ClassC { .assembly extern D2 }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2 }, assemblyName: "A").VerifyDiagnostics( // (10,13): error CS8329: Module 'CModule.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // ClassB.MethodB(null); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "ClassB.MethodB").WithArguments("CModule.dll", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C.ClassC", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10332")] [WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleTypeForwardersToTheSameAssemblyShouldNotResultInMultipleForwardError() { var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static string MethodB(ClassC obj) { return ""obj is "" + (obj == null ? ""null"" : obj.ToString()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeA = @" using B; namespace A { public class ClassA { public static void Main() { System.Console.WriteLine(ClassB.MethodB(null)); } } }"; CompileAndVerify( source: codeA, references: new MetadataReference[] { referenceB, referenceC }, expectedOutput: "obj is null"); var codeC2 = @" .assembly C { .ver 0:0:0:0 } .assembly extern D { } .class extern forwarder C.ClassC { .assembly extern D } .class extern forwarder C.ClassC { .assembly extern D }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2 }).VerifyDiagnostics( // (10,38): error CS0012: The type 'ClassC' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(ClassB.MethodB(null)); Diagnostic(ErrorCode.ERR_NoTypeDef, "ClassB.MethodB").WithArguments("C.ClassC", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 38)); var codeD = @" namespace C { public class ClassC { } }"; var referenceD = CreateCompilation(codeD, assemblyName: "D").EmitToImageReference(); CompileAndVerify( source: codeA, references: new MetadataReference[] { referenceB, referenceC2, referenceD }, expectedOutput: "obj is null"); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void CompilingModuleWithMultipleForwardersToDifferentAssembliesShouldErrorOut() { var ilSource = @" .module ForwarderModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var ilModule = GetILModuleReference(ilSource, prependDefaultHeader: false); CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule }, assemblyName: "Forwarder").VerifyDiagnostics( // error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies).WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void CompilingModuleWithMultipleForwardersToTheSameAssemblyShouldNotProduceMultipleForwardingErrors() { var ilSource = @" .assembly extern D { } .class extern forwarder Testspace.TestType { .assembly extern D } .class extern forwarder Testspace.TestType { .assembly extern D }"; var ilModule = GetILModuleReference(ilSource, prependDefaultHeader: false); CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule }).VerifyDiagnostics( // error CS0012: The type 'TestType' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("Testspace.TestType", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); var dCode = @" namespace Testspace { public class TestType { } }"; var dReference = CreateCompilation(dCode, assemblyName: "D").EmitToImageReference(); // Now compilation succeeds CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule, dReference }).VerifyDiagnostics(); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void LookingUpATypeForwardedTwiceInASourceCompilationReferenceShouldFail() { // This test specifically tests that SourceAssembly symbols also produce this error (by using a CompilationReference instead of the usual PEAssembly symbol) var ilSource = @" .module ForwarderModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var ilModuleReference = GetILModuleReference(ilSource, prependDefaultHeader: false); var forwarderCompilation = CreateEmptyCompilation( source: string.Empty, references: new MetadataReference[] { ilModuleReference }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), assemblyName: "Forwarder"); var csSource = @" namespace UserSpace { public class UserClass { public static void Main() { var obj = new Testspace.TestType(); } } }"; var userCompilation = CreateCompilation( source: csSource, references: new MetadataReference[] { forwarderCompilation.ToMetadataReference() }, assemblyName: "UserAssembly"); userCompilation.VerifyDiagnostics( // (8,37): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestType").WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 37), // (8,37): error CS0234: The type or namespace name 'TestType' does not exist in the namespace 'Testspace' (are you missing an assembly reference?) // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType").WithArguments("TestType", "Testspace").WithLocation(8, 37)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void ForwardingErrorsInLaterModulesAlwaysOverwriteOnesInEarlierModules() { var module1IL = @" .module module1IL.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var module1Reference = GetILModuleReference(module1IL, prependDefaultHeader: false); var module2IL = @" .module module12L.dll .assembly extern D3 { } .assembly extern D4 { } .class extern forwarder Testspace.TestType { .assembly extern D3 } .class extern forwarder Testspace.TestType { .assembly extern D4 }"; var module2Reference = GetILModuleReference(module2IL, prependDefaultHeader: false); var forwarderCompilation = CreateEmptyCompilation( source: string.Empty, references: new MetadataReference[] { module1Reference, module2Reference }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), assemblyName: "Forwarder"); var csSource = @" namespace UserSpace { public class UserClass { public static void Main() { var obj = new Testspace.TestType(); } } }"; var userCompilation = CreateCompilation( source: csSource, references: new MetadataReference[] { forwarderCompilation.ToMetadataReference() }, assemblyName: "UserAssembly"); userCompilation.VerifyDiagnostics( // (8,37): error CS8329: Module 'module12L.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestType").WithArguments("module12L.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,37): error CS0234: The type or namespace name 'TestType' does not exist in the namespace 'Testspace' (are you missing an assembly reference?) // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType").WithArguments("TestType", "Testspace")); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsThatChainResultInTheSameAssemblyShouldStillProduceAnError() { // The scenario is that assembly A is calling a method from assembly B. This method has a parameter of a type that lives // in assembly C. Now if assembly C is replaced with assembly C2, that forwards the type to both D and E, and D forwards it to E, // it should fail with the appropriate error. var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static void MethodB(ClassC obj) { System.Console.WriteLine(obj.GetHashCode()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeC2 = @" .assembly C { } .module C.dll .assembly extern D { } .assembly extern E { } .class extern forwarder C.ClassC { .assembly extern D } .class extern forwarder C.ClassC { .assembly extern E }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); var codeD = @" .assembly D { } .assembly extern E { } .class extern forwarder C.ClassC { .assembly extern E }"; var referenceD = CompileIL(codeD, prependDefaultHeader: false); var referenceE = CreateCompilation(codeC, assemblyName: "E").EmitToImageReference(); var codeA = @" using B; using C; namespace A { public class ClassA { public void MethodA(ClassC obj) { ClassB.MethodB(obj); } } }"; CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2, referenceD, referenceE }, assemblyName: "A").VerifyDiagnostics( // (11,13): error CS8329: Module 'C.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // ClassB.MethodB(obj); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "ClassB.MethodB").WithArguments("C.dll", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C.ClassC", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 13)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithRef() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithIn() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(in int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithOut() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithNone() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithIn() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(in int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithOut() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithNone() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithRef() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithOut() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithNone() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithRef() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithIn() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(in int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } } }
42.02359
381
0.598914
[ "MIT" ]
nbalakin/roslyn
src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs
869,344
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace QuickStart3_1 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.740741
70
0.646043
[ "MIT" ]
Microsoft/ApplicationInsights-Profiler-AspNetCore
examples/QuickStart3_1/Program.cs
695
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LanzhouBeefNoodles.Models { public class Noodle { public int Id { get; set; } public string Name { get; set; } public string ShortDescription { get; set; } public string LongDescription { get; set; } public decimal Price { get; set; } public string ImageUrl { get; set; } public bool IsInStock { get; set; } } }
25.736842
52
0.635992
[ "MIT" ]
Rico00121/MyFirstWebApp
Models/Noodle.cs
491
C#
using System.Collections.Generic; using System.Reflection; using System.Text.Json; using Moq; using Reductech.Sequence.ConnectorManagement.Base; namespace Reductech.Sequence.ConnectorManagement.Tests; public class ConnectorSettingsTests { [Fact] public void DefaultForAssembly_ByDefault_ReturnsAssemblyInformation() { const string name = "test"; const string version = "0.9.0"; var assembly = new Mock<Assembly>(); assembly.Setup(a => a.GetName()).Returns(() => new AssemblyName(name)); assembly.Setup(a => a.GetCustomAttributes(It.IsAny<Type>(), true)) // ReSharper disable once CoVariantArrayConversion .Returns(() => new Attribute[] { new AssemblyInformationalVersionAttribute(version) }); var settings = ConnectorSettings.DefaultForAssembly(assembly.Object); Assert.Equal(name, settings.Id); Assert.Equal(version, settings.Version); Assert.True(settings.Enable); } [Fact] public void DefaultForAssembly_WhenNameAndVersionAreNull_ReturnsUnknown() { const string unknown = "Unknown"; var assembly = new Mock<Assembly>(); assembly.Setup(a => a.GetName()).Returns(() => new AssemblyName()); assembly.Setup(a => a.GetCustomAttributes(It.IsAny<Type>(), true)) .Returns(Array.Empty<Attribute>); var settings = ConnectorSettings.DefaultForAssembly(assembly.Object); Assert.Equal(unknown, settings.Id); Assert.Equal(unknown, settings.Version); } [Fact] public void Settings_IsCorrectlyDeserialized() { var expectedFeatures = new[] { "ANALYSIS", "CASE_CREATION" }; var settings = JsonSerializer.Deserialize<Dictionary<string, ConnectorSettings>>( Helpers.TestConfiguration )!; var nuixSettings = settings["Reductech.Sequence.Connectors.Nuix"]; Assert.NotNull(nuixSettings.Settings); Assert.Equal("dongle", nuixSettings.Settings!["licencesourcetype"].ToString()); var nuixFeatures = (JsonElement)nuixSettings.Settings!["features"]; Assert.NotNull(nuixFeatures); Assert.Equal(JsonValueKind.Array, nuixFeatures.ValueKind); var actualFeatures = ToIEnumerable(nuixFeatures.EnumerateArray()) .Select(x => x.GetString()!) .ToArray(); Assert.Equal(expectedFeatures, actualFeatures); static IEnumerable<T> ToIEnumerable<T>(IEnumerator<T> enumerator) { while (enumerator.MoveNext()) { yield return enumerator.Current; } } } }
32.156627
99
0.651555
[ "Apache-2.0" ]
reductech/ConnectorManager
ConnectorManager.Tests/ConnectorSettingsTests.cs
2,671
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; using TMPro; using UnityEngine.UI; using DG.Tweening; public class SpawnedObjectManager : MonoBehaviour { [Tooltip("The keyboard button to activate the gravity.")] public KeyCode kinematicActivateKey = KeyCode.Space; [Tooltip("The UI text to show the gravity key button.")] public TextMeshProUGUI kinematicKeyText; [Tooltip("The UI image for the play mode.")] public Image playImage; [Tooltip("The UI image for the pause mode.")] public Image pauseImage; [Tooltip("Post Process manager, leave this empty (null) if you don't want to switch effects between kinematic and non-kinematic mode")] public PostProcessManager postProcessManager; [Tooltip("Audio Controller to allow changing the audio based on kinematic and non-kinematic (physics on) mode")] public AudioController audioController; List<GameObject> spawnedBodies = new List<GameObject>(); bool isKinematic = true; void Start(){ kinematicKeyText.text = kinematicActivateKey.ToString().ToUpper(); setImages(isKinematic); } /// <summary> /// Add a GameObject to the spawned list. /// </summary> public void AddObject(GameObject o) { handleGravity(o, isKinematic); spawnedBodies.Add(o); } /// <summary> /// Handles the rigidbodies and the colliders of the root object /// </summary> void handleGravity(GameObject o, bool isKinematicBody) { var rigidbodies = o.GetComponentsInChildren<Rigidbody>(); var colliders = o.GetComponentsInChildren<Collider>(); foreach (var rb in rigidbodies) rb.isKinematic = isKinematicBody; foreach (var coll in colliders) coll.isTrigger = isKinematicBody; } /// <summary> /// Check if a GameObject was in the list and if found destroy it. /// </summary> public bool CheckAndDestroyObject(GameObject o) { if(spawnedBodies.Remove(o)) { o.transform.DOScale(0, .1f).SetEase(Ease.InBack).OnComplete(() => Destroy(o)); return true; } return false; } /// <summary> /// Activate the gravity for all the spawned objects. /// </summary> void ActivateGravity(bool isKinematicBody) { spawnedBodies = spawnedBodies.Where(x => x != null).ToList(); foreach(var b in spawnedBodies) { handleGravity(b, isKinematicBody); } } void Update() { if(Input.GetKeyUp(kinematicActivateKey)){ isKinematic = !isKinematic; setImages(isKinematic); if (postProcessManager != null) { if (isKinematic) postProcessManager.ChangeVolume(Mode.kinematic); else postProcessManager.ChangeVolume(Mode.nonKinematic); } if (audioController != null) { if (isKinematic) audioController.LowpassAudio(); else audioController.RemoveLowpassEffect(); } ActivateGravity(isKinematic); } } /// <summary> /// Toggle the play/pause UI images based on the current state. /// </summary> void setImages(bool v) { var playColor = playImage.color; playColor.a = v ?.3f : 1f; playImage.color = playColor; var pauseColor = pauseImage.color; pauseColor.a = v ? 1f : .3f; pauseImage.color = pauseColor; } }
28.629921
139
0.608361
[ "MIT" ]
alikrc/Unity-Physics-Sandbox
Assets/Scripts/Game/SpawnedObjectManager.cs
3,638
C#
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------------------------------------------ using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Microsoft.PSharp.TestingServices.Tests { public class CreateMachineIdFromNameTest : BaseTest { public CreateMachineIdFromNameTest(ITestOutputHelper output) : base(output) { } private class E : Event { } private class LivenessMonitor : Monitor { [Start] [Hot] [OnEventGotoState(typeof(E), typeof(S2))] private class S1 : MonitorState { } [Hot] [OnEventGotoState(typeof(E), typeof(S3))] private class S2 : MonitorState { } [Cold] private class S3 : MonitorState { } } private class M : Machine { [Start] [OnEntry(nameof(InitOnEntry))] private class Init : MachineState { } private void InitOnEntry() { this.Monitor(typeof(LivenessMonitor), new E()); } } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName1() { this.Test(r => { r.RegisterMonitor(typeof(LivenessMonitor)); var m1 = r.CreateMachine(typeof(M)); var m2 = r.CreateMachineIdFromName(typeof(M), "M"); r.Assert(!m1.Equals(m2)); r.CreateMachine(m2, typeof(M)); }); } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName2() { this.Test(r => { r.RegisterMonitor(typeof(LivenessMonitor)); var m1 = r.CreateMachineIdFromName(typeof(M), "M1"); var m2 = r.CreateMachineIdFromName(typeof(M), "M2"); r.Assert(!m1.Equals(m2)); r.CreateMachine(m1, typeof(M)); r.CreateMachine(m2, typeof(M)); }); } private class M2 : Machine { [Start] private class S : MachineState { } } private class M3 : Machine { [Start] private class S : MachineState { } } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName4() { this.TestWithError(r => { var m3 = r.CreateMachineIdFromName(typeof(M3), "M3"); r.CreateMachine(m3, typeof(M2)); }, expectedError: "Cannot bind machine id '' of type 'M3' to a machine of type 'M2'.", replay: true); } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName5() { this.TestWithError(r => { var m1 = r.CreateMachineIdFromName(typeof(M2), "M2"); r.CreateMachine(m1, typeof(M2)); r.CreateMachine(m1, typeof(M2)); }, expectedError: "Machine with id '' is already bound to an existing machine.", replay: true); } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName6() { this.TestWithError(r => { var m = r.CreateMachineIdFromName(typeof(M2), "M2"); r.SendEvent(m, new E()); }, expectedError: "Cannot send event 'E' to machine id '' that was never previously bound to a machine of type 'M2'", replay: true); } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName7() { this.TestWithError(r => { var m = r.CreateMachineIdFromName(typeof(M2), "M2"); r.CreateMachine(m, typeof(M2)); // Make sure that the machine halts. for (int i = 0; i < 100; i++) { r.SendEvent(m, new Halt()); } // Trying to bring up a halted machine. r.CreateMachine(m, typeof(M2)); }, configuration: GetConfiguration(), expectedErrors: new string[] { // Note: because RunMachineEventHandler is async, the halted machine // may or may not be removed by the time we call CreateMachine. "Machine with id '' is already bound to an existing machine.", "Machine id '' of a previously halted machine cannot be reused to create a new machine of type 'M2'" }); } private class E2 : Event { public MachineId Mid; public E2(MachineId mid) { this.Mid = mid; } } private class M4 : Machine { [Start] [OnEventDoAction(typeof(E), nameof(Process))] private class S : MachineState { } private void Process() { this.Monitor<WaitUntilDone>(new Done()); } } private class M5 : Machine { [Start] [OnEntry(nameof(InitOnEntry))] private class S : MachineState { } private void InitOnEntry() { var mid = (this.ReceivedEvent as E2).Mid; this.Send(mid, new E()); } } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName8() { var configuration = Configuration.Create(); configuration.SchedulingIterations = 100; configuration.ReductionStrategy = Utilities.ReductionStrategy.None; this.TestWithError(r => { var m = r.CreateMachineIdFromName(typeof(M4), "M4"); r.CreateMachine(typeof(M5), new E2(m)); r.CreateMachine(m, typeof(M4)); }, configuration, "Cannot send event 'E' to machine id '' that was never previously bound to a machine of type 'M4'", false); } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName9() { this.Test(r => { var m1 = r.CreateMachineIdFromName(typeof(M4), "M4"); var m2 = r.CreateMachineIdFromName(typeof(M4), "M4"); r.Assert(m1.Equals(m2)); }); } private class M6 : Machine { [Start] [OnEntry(nameof(InitOnEntry))] private class Init : MachineState { } private void InitOnEntry() { var m = this.Runtime.CreateMachineIdFromName(typeof(M4), "M4"); this.CreateMachine(m, typeof(M4), "friendly"); } } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName10() { this.TestWithError(r => { r.CreateMachine(typeof(M6)); r.CreateMachine(typeof(M6)); }, expectedError: "Machine with id '' is already bound to an existing machine.", replay: true); } private class Done : Event { } private class WaitUntilDone : Monitor { [Start] [Hot] [OnEventGotoState(typeof(Done), typeof(S2))] private class S1 : MonitorState { } [Cold] private class S2 : MonitorState { } } private class M7 : Machine { [Start] [OnEntry(nameof(InitOnEntry))] private class Init : MachineState { } private async Task InitOnEntry() { await this.Runtime.CreateMachineAndExecute(typeof(M6)); var m = this.Runtime.CreateMachineIdFromName(typeof(M4), "M4"); this.Runtime.SendEvent(m, new E()); } } [Fact(Timeout=5000)] public void TestCreateMachineIdFromName11() { this.Test(r => { r.RegisterMonitor(typeof(WaitUntilDone)); r.CreateMachine(typeof(M7)); }); } } }
28.964052
126
0.466321
[ "MIT" ]
alexsyeo/PSharp
Tests/TestingServices.Tests/Runtime/CreateMachineIdFromNameTest.cs
8,865
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using System; using System.Collections.Generic; using System.Net; using Azure.Core.Pipeline; using Azure.Core.Testing; using Azure.Storage.Queues.Models; using Azure.Storage.Sas; using Azure.Storage.Test; using Azure.Storage.Test.Shared; namespace Azure.Storage.Queues.Tests { public class QueueTestBase : StorageTestBase { public string GetNewQueueName() => $"test-queue-{this.Recording.Random.NewGuid()}"; public string GetNewMessageId() => $"test-message-{this.Recording.Random.NewGuid()}"; public QueueTestBase(bool async) : this(async, null) { } public QueueTestBase(bool async, RecordedTestMode? mode = null) : base(async, mode) { } public QueueClientOptions GetOptions() => this.Recording.InstrumentClientOptions( new QueueClientOptions { Diagnostics = { IsLoggingEnabled = true }, Retry = { Mode = RetryMode.Exponential, MaxRetries = Azure.Storage.Constants.MaxReliabilityRetries, Delay = TimeSpan.FromSeconds(this.Mode == RecordedTestMode.Playback ? 0.01 : 0.5), MaxDelay = TimeSpan.FromSeconds(this.Mode == RecordedTestMode.Playback ? 0.1 : 10) } }); public QueueServiceClient GetServiceClient_SharedKey() => this.InstrumentClient( new QueueServiceClient( new Uri(this.TestConfigDefault.QueueServiceEndpoint), new StorageSharedKeyCredential( this.TestConfigDefault.AccountName, this.TestConfigDefault.AccountKey), this.GetOptions())); public QueueServiceClient GetServiceClient_AccountSas(StorageSharedKeyCredential sharedKeyCredentials = default, SasQueryParameters sasCredentials = default) => this.InstrumentClient( new QueueServiceClient( new Uri($"{this.TestConfigDefault.QueueServiceEndpoint}?{sasCredentials ?? this.GetNewAccountSasCredentials(sharedKeyCredentials ?? this.GetNewSharedKeyCredentials())}"), this.GetOptions())); public QueueServiceClient GetServiceClient_QueueServiceSas(string queueName, StorageSharedKeyCredential sharedKeyCredentials = default, SasQueryParameters sasCredentials = default) => this.InstrumentClient( new QueueServiceClient( new Uri($"{this.TestConfigDefault.QueueServiceEndpoint}?{sasCredentials ?? this.GetNewQueueServiceSasCredentials(queueName, sharedKeyCredentials ?? this.GetNewSharedKeyCredentials())}"), this.GetOptions())); public QueueServiceClient GetServiceClient_OauthAccount() => this.GetServiceClientFromOauthConfig(this.TestConfigOAuth); private QueueServiceClient GetServiceClientFromOauthConfig(TenantConfiguration config) => this.InstrumentClient( new QueueServiceClient( new Uri(config.QueueServiceEndpoint), this.GetOAuthCredential(config), this.GetOptions())); public IDisposable GetNewQueue(out QueueClient queue, QueueServiceClient service = default, IDictionary<string, string> metadata = default) { var containerName = this.GetNewQueueName(); service ??= this.GetServiceClient_SharedKey(); queue = this.InstrumentClient(service.GetQueueClient(containerName)); return new DisposingQueue(queue, metadata ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)); } public StorageSharedKeyCredential GetNewSharedKeyCredentials() => new StorageSharedKeyCredential( this.TestConfigDefault.AccountName, this.TestConfigDefault.AccountKey); public SasQueryParameters GetNewAccountSasCredentials(StorageSharedKeyCredential sharedKeyCredentials = default) => new AccountSasBuilder { Protocol = SasProtocol.None, Services = new AccountSasServices { Queues = true }.ToString(), ResourceTypes = new AccountSasResourceTypes { Container = true }.ToString(), StartTime = this.Recording.UtcNow.AddHours(-1), ExpiryTime = this.Recording.UtcNow.AddHours(+1), Permissions = new QueueAccountSasPermissions { Read = true, Write = true, Update = true, Process = true, Add = true, Delete = true, List = true }.ToString(), IPRange = new IPRange(IPAddress.None, IPAddress.None) }.ToSasQueryParameters(sharedKeyCredentials); public SasQueryParameters GetNewQueueServiceSasCredentials(string queueName, StorageSharedKeyCredential sharedKeyCredentials = default) => new QueueSasBuilder { QueueName = queueName, Protocol = SasProtocol.None, StartTime = this.Recording.UtcNow.AddHours(-1), ExpiryTime = this.Recording.UtcNow.AddHours(+1), Permissions = new QueueAccountSasPermissions { Read = true, Update = true, Process = true, Add = true }.ToString(), IPRange = new IPRange(IPAddress.None, IPAddress.None) }.ToSasQueryParameters(sharedKeyCredentials ?? this.GetNewSharedKeyCredentials()); class DisposingQueue : IDisposable { public QueueClient QueueClient { get; } public DisposingQueue(QueueClient queue, IDictionary<string, string> metadata) { queue.CreateAsync(metadata: metadata).Wait(); this.QueueClient = queue; } public void Dispose() { if (this.QueueClient != null) { try { this.QueueClient.DeleteAsync().Wait(); } catch { // swallow the exception to avoid hiding another test failure } } } } public SignedIdentifier[] BuildSignedIdentifiers() => new[] { new SignedIdentifier { Id = this.GetNewString(), AccessPolicy = new AccessPolicy { Start = this.Recording.UtcNow.AddHours(-1), Expiry = this.Recording.UtcNow.AddHours(1), Permission = "raup" } } }; } }
45.74026
206
0.593129
[ "MIT" ]
StanleyGoldman/azure-sdk-for-net
sdk/storage/Azure.Storage.Queues/tests/QueueTestBase.cs
7,046
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyDirectoryHelper.cs" company="WildGums"> // Copyright (c) 2008 - 2017 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orc.Csv.Tests { using System; using Catel.IO; internal static class AssemblyDirectoryHelper { #region Methods public static string GetCurrentDirectory() { var directory = AppDomain.CurrentDomain.BaseDirectory; return directory; } public static string Resolve(string fileName) { return Path.Combine(GetCurrentDirectory(), fileName); } #endregion } }
31.035714
120
0.453395
[ "MIT" ]
Orcomp/Orc.CsvHelper
src/Orc.Csv.Tests/Helpers/AssemblyDirectoryHelper.cs
871
C#
// -------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // -------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Edna.Utils.Http { public static class HttpHeadersExtensions { private static readonly string[] PossibleEmailClaimTypes = { "email", "upn", "unique_name" }; private static readonly JwtSecurityTokenHandler JwtSecurityTokenHandler = new JwtSecurityTokenHandler(); public static bool TryGetTokenClaims(this IHeaderDictionary headers, out Claim[] claims, Action<string> logAction = null) { claims = null; if (!headers.ContainsKey("Authorization")) { logAction?.Invoke("No Authorization header was found in the request."); return false; } string authorizationContent = headers["Authorization"].ToString(); string token = authorizationContent?.Split(' ')[1]; if (string.IsNullOrEmpty(token)) { logAction?.Invoke("Could not get JWT from the request."); return false; } if (!(JwtSecurityTokenHandler.ReadToken(token) is JwtSecurityToken jwt)) { logAction?.Invoke("Token is not a valid JWT."); return false; } claims = jwt.Claims.ToArray(); return true; } } }
36.52
130
0.53943
[ "MIT" ]
gregorypilar/Learn-LTI
backend/Utils/Edna.Utils.Http/Edna.Utils.Http/HttpHeadersExtensions.cs
1,828
C#
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Amazon.IonDotnet.Tree.Impl { using System.Diagnostics; /// <inheritdoc /> /// <summary> /// An ion datagram is a special kind of value which represents a stream of Ion values. /// </summary> internal sealed class IonDatagram : IonSequence, IIonDatagram { public IonDatagram() : base(false) { } /// <inheritdoc /> /// <summary> /// Use strict reference equality for datagram. /// </summary> public override bool IsEquivalentTo(IIonValue other) => other == this; public override IonType Type() => IonType.Datagram; /// <summary> /// Adding an item to the datagram will mark the current symbol table. /// </summary> /// <param name="item">The IIonValue to add.</param> public override void Add(IIonValue item) { base.Add(item); Debug.Assert(item != null, nameof(item) + " != null"); } public int GetHashCode(IonValue obj) => obj.GetHashCode(); } }
31.826923
91
0.628399
[ "Apache-2.0" ]
Armanbqt/ion-dotnet
Amazon.IonDotnet/Tree/Impl/IonDatagram.cs
1,655
C#
using System.Threading.Tasks; using Deployer.Gui; using Deployer.Raspberry.Gui.ViewModels; using Deployer.Tasks; namespace Deployer.Raspberry.Gui.Specifics { public class WpfMarkdownDisplayer : IMarkdownDisplayer { private readonly UIServices services; public WpfMarkdownDisplayer(UIServices services) { this.services = services; } public Task Display(string title, string message) { services.ViewService.Show("MarkdownViewer", new MessageViewModel(title, message)); return Task.CompletedTask; } } }
26.347826
94
0.676568
[ "MIT" ]
atumangh/WOA-Deployer-Rpi
Source/Deployer.Raspberry.Gui/Specifics/WpfMarkdownDisplayer.cs
606
C#
using Codeizi.CQRS.Saga.Context; using Codeizi.CQRS.Saga.Data; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Codeizi.CQRS.Saga { public class Saga { private readonly SagaContext _db; public Saga(SagaContext db) : this() => _db = db; private readonly List<Type> actions; private Saga() => actions = new List<Type>(); protected Saga AddActionSaga(Type actionSaga) { if (!CheckTypeIsAction(actionSaga)) throw new ArgumentException($"{nameof(actionSaga)} not implementation {nameof(IActionSaga)}"); actions.Add(actionSaga); return this; } protected Saga AddActionSaga<T>() where T : class => AddActionSaga(typeof(T)); private bool CheckTypeIsAction(Type type) => type.GetInterfaces().Contains(typeof(IActionSaga)); public async Task<Guid> Start(object initialState) { var idSaga = Guid.NewGuid(); var state = new State(idSaga) { Value = initialState }; await AddSaga(idSaga); await AddSagaActions(idSaga, initialState.GetType().FullName); await AddStateSaga(idSaga, state); await _db.SaveChangesAsync(); return idSaga; } private async Task AddSaga(Guid idSaga) { await _db.SagaInfo.AddAsync(new SagaInfo { CreationDate = DateTime.Now, Id = idSaga, }); } private async Task AddStateSaga(Guid idSaga, State state) { var sagaState = new SagaState { SagaInfoId = idSaga, ExtendedData = JsonConvert.SerializeObject(state.Value) }; await _db.States.AddRangeAsync(sagaState); } private async Task AddSagaActions(Guid id, string typeState) { byte position = 0; var sagaActions = actions.ConvertAll(new Converter<Type, SagaAction>((type) => { position++; return new SagaAction() { IdSaga = id, Status = StatusOperation.Wait, Type = type.FullName, Position = position, TypeState = typeState, Created = DateTime.Now, }; })); await _db.AddRangeAsync(sagaActions); } } }
27.670103
110
0.525335
[ "MIT" ]
JDouglasMendes/codeizi-cqrs-saga
src/Codeizi.CQRS.Saga/Saga.cs
2,686
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class BTests { [TestMethod] public void TestMethod1() { var input = @"5 4 4 9 7 5"; var output = @"5"; Tester.InOutTest(() => Tasks.B.Solve(), input, output); } [TestMethod] public void TestMethod2() { var input = @"6 4 5 4 3 3 5"; var output = @"8"; Tester.InOutTest(() => Tasks.B.Solve(), input, output); } [TestMethod] public void TestMethod3() { var input = @"10 9 4 6 1 9 6 10 6 6 8"; var output = @"39"; Tester.InOutTest(() => Tasks.B.Solve(), input, output); } [TestMethod] public void TestMethod4() { var input = @"2 1 1"; var output = @"0"; Tester.InOutTest(() => Tasks.B.Solve(), input, output); } } }
22.066667
67
0.463243
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC175/Tests/BTests.cs
993
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.CosmosDB { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// CollectionRegionOperations operations. /// </summary> public partial interface ICollectionRegionOperations { /// <summary> /// Retrieves the metrics determined by the given filter for the given /// database account, collection and region. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='accountName'> /// Cosmos DB database account name. /// </param> /// <param name='region'> /// Cosmos DB region, with spaces between words and each word /// capitalized. /// </param> /// <param name='databaseRid'> /// Cosmos DB database rid. /// </param> /// <param name='collectionRid'> /// Cosmos DB collection rid. /// </param> /// <param name='filter'> /// An OData filter expression that describes a subset of metrics to /// return. The parameters that can be filtered are name.value (name of /// the metric, can have an or of multiple names), startTime, endTime, /// and timeGrain. The supported operator is eq. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<Metric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string accountName, string region, string databaseRid, string collectionRid, string filter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
41.257143
330
0.639543
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/ICollectionRegionOperations.cs
2,888
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BfresLibrary.Switch.Core; using BfresLibrary.Core; using BfresLibrary; namespace BfresLibrary.Switch { internal class FogAnimParser { public static void Read(ResFileSwitchLoader loader, FogAnim fogAnim) { if (loader.ResFile.VersionMajor2 == 9) { fogAnim.Flags = loader.ReadEnum<FogAnimFlags>(true); loader.Seek(2); } else loader.LoadHeaderBlock(); fogAnim.Name = loader.LoadString(); long CurveArrayOffset = loader.ReadInt64(); fogAnim.BaseData = loader.LoadCustom(() => new FogAnimData(loader)); fogAnim.UserData = loader.LoadDictValues<UserData>(); fogAnim.DistanceAttnFuncName = loader.LoadString(); ushort numUserData = 0; byte numCurve = 0; if (loader.ResFile.VersionMajor2 == 9) { fogAnim.FrameCount = loader.ReadInt32(); numCurve = loader.ReadByte(); fogAnim.DistanceAttnFuncIndex = loader.ReadSByte(); numUserData = loader.ReadUInt16(); fogAnim.BakedSize = loader.ReadUInt32(); loader.Seek(4); } else { fogAnim.Flags = loader.ReadEnum<FogAnimFlags>(true); loader.Seek(2); fogAnim.FrameCount = loader.ReadInt32(); numCurve = loader.ReadByte(); fogAnim.DistanceAttnFuncIndex = loader.ReadSByte(); numUserData = loader.ReadUInt16(); fogAnim.BakedSize = loader.ReadUInt32(); } fogAnim.Curves = loader.LoadList<AnimCurve>(numCurve); } public static void Write(ResFileSwitchSaver saver, FogAnim fogAnim) { if (saver.ResFile.VersionMajor2 == 9) { saver.Write(fogAnim.Flags, true); saver.Seek(2); } else saver.Seek(12); saver.SaveRelocateEntryToSection(saver.Position, 6, 1, 0, ResFileSwitchSaver.Section1, "Fog Animation"); saver.SaveString(fogAnim.Name); fogAnim.PosCurveArrayOffset = saver.SaveOffset(); fogAnim.PosBaseDataOffset = saver.SaveOffset(); fogAnim.PosUserDataOffset = saver.SaveOffset(); fogAnim.PosUserDataDictOffset = saver.SaveOffset(); saver.SaveString(fogAnim.DistanceAttnFuncName); if (saver.ResFile.VersionMajor2 == 9) { saver.Write(fogAnim.FrameCount); saver.Write((byte)fogAnim.Curves.Count); saver.Write(fogAnim.DistanceAttnFuncIndex); saver.Write((ushort)fogAnim.UserData.Count); saver.Write(fogAnim.BakedSize); saver.Seek(4); } else { saver.Write(fogAnim.Flags, true); saver.Seek(2); saver.Write(fogAnim.FrameCount); saver.Write((byte)fogAnim.Curves.Count); saver.Write(fogAnim.DistanceAttnFuncIndex); saver.Write((ushort)fogAnim.UserData.Count); saver.Write(fogAnim.BakedSize); } } } }
36.612903
116
0.553598
[ "MIT" ]
Jenrikku/BfresLibrary
BfresLibrary/Switch/SceneAnim/FogAnimParser.cs
3,407
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AccidentalNoise { public class ScaleOffset : ModuleBase { double scale, offset; public ScaleOffset(double scale, double offset, ModuleBase mbase) { this.scale = scale; this.offset = offset; this.Source = mbase; } public override double Get(double x, double y) { return Source.Get(x, y) * scale + offset; } } }
22
74
0.56
[ "MIT" ]
hkilian/pixelplanets
Assets/Plugins/AccidentalNoise/ScaleOffset.cs
552
C#
using System; using System.Collections.Generic; using AeroGear.Mobile.Core.Utils; using AeroGear.Mobile.Security.Executors; using Moq; using NUnit.Framework; namespace AeroGear.Mobile.Security.Tests { [TestFixture(Category = "Executors")] public class SyncCheckExecutorTest { private ISecurityCheck mockSecurityCheck; private ISecurityCheckFactory mockCheckFactory; private ISecurityCheckType mockSecurityCheckType; [SetUp] public void SetUp() { mockSecurityCheckType = new Mock<ISecurityCheckType>().Object; var mock = new Mock<ISecurityCheck>(); mockSecurityCheck = mock.Object; mock.Setup(mockSecurityCheck => mockSecurityCheck.GetId()).Returns("test-id"); mock.Setup(mockSecurityCheck => mockSecurityCheck.GetName()).Returns("test-name"); SecurityCheckResult result = new SecurityCheckResult(mockSecurityCheck, true); mock.Setup(mockSecurityCheck => mockSecurityCheck.Check()).Returns(result); var mockSecurityCheckFactory = new Mock<ISecurityCheckFactory>(); this.mockCheckFactory = mockSecurityCheckFactory.Object; mockSecurityCheckFactory.Setup(mockCheckFactory => mockCheckFactory.create(mockSecurityCheckType)).Returns(mockSecurityCheck); ServiceFinder.RegisterInstance<ISecurityCheckFactory>(mockCheckFactory); } [Test] public void TestExecuteSyncSingle() { Dictionary<String, SecurityCheckResult> results = SecurityCheckExecutor.newSyncExecutor() .WithSecurityCheck(mockSecurityCheckType) .Build() .Execute(); Assert.AreEqual(1, results.Count); Assert.IsTrue(results.ContainsKey(mockSecurityCheck.GetId())); Assert.IsTrue(results[mockSecurityCheck.GetId()].Passed); } } }
36.690909
138
0.648662
[ "Apache-2.0" ]
wojta/aerogear-xamarin-sdk
Security.Tests/Executors/SyncCheckExecutorTest.cs
2,020
C#
using ServiceLocator; public class ZpoppetCharacter : CharacterBase { public ZpoppetCharacter(StatsBase baseStat) : base(baseStat) { } }
17.555556
64
0.696203
[ "Apache-2.0" ]
Bellseboss-Studio/ProyectoPrincipal_JuegoDePeleas
Assets/Scripts/Characters/ZpoppetCharacter.cs
160
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; internal class test { private static Int64 f00(Int64 x, Int64 y) { x = x + y; return x; } private static Int64 f01(Int64 x, Int64 y) { x = x - y; return x; } private static Int64 f02(Int64 x, Int64 y) { x = x * y; return x; } private static Int64 f03(Int64 x, Int64 y) { x = x / y; return x; } private static Int64 f04(Int64 x, Int64 y) { x = x % y; return x; } private static Int64 f05(Int64 x, Int64 y) { x = x << (int)y; return x; } private static Int64 f06(Int64 x, Int64 y) { x = x >> (int)y; return x; } private static Int64 f07(Int64 x, Int64 y) { x = x & y; return x; } private static Int64 f08(Int64 x, Int64 y) { x = x ^ y; return x; } private static Int64 f09(Int64 x, Int64 y) { x = x | y; return x; } private static Int64 f10(Int64 x, Int64 y) { x += x + y; return x; } private static Int64 f11(Int64 x, Int64 y) { x += x - y; return x; } private static Int64 f12(Int64 x, Int64 y) { x += x * y; return x; } private static Int64 f13(Int64 x, Int64 y) { x += x / y; return x; } private static Int64 f14(Int64 x, Int64 y) { x += x % y; return x; } private static Int64 f15(Int64 x, Int64 y) { x += x << (int)y; return x; } private static Int64 f16(Int64 x, Int64 y) { x += x >> (int)y; return x; } private static Int64 f17(Int64 x, Int64 y) { x += x & y; return x; } private static Int64 f18(Int64 x, Int64 y) { x += x ^ y; return x; } private static Int64 f19(Int64 x, Int64 y) { x += x | y; return x; } private static Int64 f20(Int64 x, Int64 y) { x -= x + y; return x; } private static Int64 f21(Int64 x, Int64 y) { x -= x - y; return x; } private static Int64 f22(Int64 x, Int64 y) { x -= x * y; return x; } private static Int64 f23(Int64 x, Int64 y) { x -= x / y; return x; } private static Int64 f24(Int64 x, Int64 y) { x -= x % y; return x; } private static Int64 f25(Int64 x, Int64 y) { x -= x << (int)y; return x; } private static Int64 f26(Int64 x, Int64 y) { x -= x >> (int)y; return x; } private static Int64 f27(Int64 x, Int64 y) { x -= x & y; return x; } private static Int64 f28(Int64 x, Int64 y) { x -= x ^ y; return x; } private static Int64 f29(Int64 x, Int64 y) { x -= x | y; return x; } private static Int64 f30(Int64 x, Int64 y) { x *= x + y; return x; } private static Int64 f31(Int64 x, Int64 y) { x *= x - y; return x; } private static Int64 f32(Int64 x, Int64 y) { x *= x * y; return x; } private static Int64 f33(Int64 x, Int64 y) { x *= x / y; return x; } private static Int64 f34(Int64 x, Int64 y) { x *= x % y; return x; } private static Int64 f35(Int64 x, Int64 y) { x *= x << (int)y; return x; } private static Int64 f36(Int64 x, Int64 y) { x *= x >> (int)y; return x; } private static Int64 f37(Int64 x, Int64 y) { x *= x & y; return x; } private static Int64 f38(Int64 x, Int64 y) { x *= x ^ y; return x; } private static Int64 f39(Int64 x, Int64 y) { x *= x | y; return x; } private static Int64 f40(Int64 x, Int64 y) { x /= x + y; return x; } private static Int64 f41(Int64 x, Int64 y) { x /= x - y; return x; } private static Int64 f42(Int64 x, Int64 y) { x /= x * y; return x; } private static Int64 f43(Int64 x, Int64 y) { x /= x / y; return x; } private static Int64 f44(Int64 x, Int64 y) { x /= x % y; return x; } private static Int64 f45(Int64 x, Int64 y) { x /= x << (int)y; return x; } private static Int64 f46(Int64 x, Int64 y) { x /= x >> (int)y; return x; } private static Int64 f47(Int64 x, Int64 y) { x /= x & y; return x; } private static Int64 f48(Int64 x, Int64 y) { x /= x ^ y; return x; } private static Int64 f49(Int64 x, Int64 y) { x /= x | y; return x; } private static Int64 f50(Int64 x, Int64 y) { x %= x + y; return x; } private static Int64 f51(Int64 x, Int64 y) { x %= x - y; return x; } private static Int64 f52(Int64 x, Int64 y) { x %= x * y; return x; } private static Int64 f53(Int64 x, Int64 y) { x %= x / y; return x; } private static Int64 f54(Int64 x, Int64 y) { x %= x % y; return x; } private static Int64 f55(Int64 x, Int64 y) { x %= x << (int)y; return x; } private static Int64 f56(Int64 x, Int64 y) { x %= x >> (int)y; return x; } private static Int64 f57(Int64 x, Int64 y) { x %= x & y; return x; } private static Int64 f58(Int64 x, Int64 y) { x %= x ^ y; return x; } private static Int64 f59(Int64 x, Int64 y) { x %= x | y; return x; } private static Int64 f60(Int64 x, Int64 y) { x <<= (int)(x + y); return x; } private static Int64 f61(Int64 x, Int64 y) { x <<= (int)(x - y); return x; } private static Int64 f62(Int64 x, Int64 y) { x <<= (int)(x * y); return x; } private static Int64 f63(Int64 x, Int64 y) { x <<= (int)(x / y); return x; } private static Int64 f64(Int64 x, Int64 y) { x <<= (int)(x % y); return x; } private static Int64 f65(Int64 x, Int64 y) { x <<= (int)(x << (int)y); return x; } private static Int64 f66(Int64 x, Int64 y) { x <<= (int)(x >> (int)y); return x; } private static Int64 f67(Int64 x, Int64 y) { x <<= (int)(x & y); return x; } private static Int64 f68(Int64 x, Int64 y) { x <<= (int)(x ^ y); return x; } private static Int64 f69(Int64 x, Int64 y) { x <<= (int)(x | y); return x; } private static Int64 f70(Int64 x, Int64 y) { x >>= (int)(x + y); return x; } private static Int64 f71(Int64 x, Int64 y) { x >>= (int)(x - y); return x; } private static Int64 f72(Int64 x, Int64 y) { x >>= (int)(x * y); return x; } private static Int64 f73(Int64 x, Int64 y) { x >>= (int)(x / y); return x; } private static Int64 f74(Int64 x, Int64 y) { x >>= (int)(x % y); return x; } private static Int64 f75(Int64 x, Int64 y) { x >>= (int)(x << (int)y); return x; } private static Int64 f76(Int64 x, Int64 y) { x >>= (int)(x >> (int)y); return x; } private static Int64 f77(Int64 x, Int64 y) { x >>= (int)(x & y); return x; } private static Int64 f78(Int64 x, Int64 y) { x >>= (int)(x ^ y); return x; } private static Int64 f79(Int64 x, Int64 y) { x >>= (int)(x | y); return x; } private static Int64 f80(Int64 x, Int64 y) { x &= x + y; return x; } private static Int64 f81(Int64 x, Int64 y) { x &= x - y; return x; } private static Int64 f82(Int64 x, Int64 y) { x &= x * y; return x; } private static Int64 f83(Int64 x, Int64 y) { x &= x / y; return x; } private static Int64 f84(Int64 x, Int64 y) { x &= x % y; return x; } private static Int64 f85(Int64 x, Int64 y) { x &= x << (int)y; return x; } private static Int64 f86(Int64 x, Int64 y) { x &= x >> (int)y; return x; } private static Int64 f87(Int64 x, Int64 y) { x &= x & y; return x; } private static Int64 f88(Int64 x, Int64 y) { x &= x ^ y; return x; } private static Int64 f89(Int64 x, Int64 y) { x &= x | y; return x; } private static Int64 f90(Int64 x, Int64 y) { x ^= x + y; return x; } private static Int64 f91(Int64 x, Int64 y) { x ^= x - y; return x; } private static Int64 f92(Int64 x, Int64 y) { x ^= x * y; return x; } private static Int64 f93(Int64 x, Int64 y) { x ^= x / y; return x; } private static Int64 f94(Int64 x, Int64 y) { x ^= x % y; return x; } private static Int64 f95(Int64 x, Int64 y) { x ^= x << (int)y; return x; } private static Int64 f96(Int64 x, Int64 y) { x ^= x >> (int)y; return x; } private static Int64 f97(Int64 x, Int64 y) { x ^= x & y; return x; } private static Int64 f98(Int64 x, Int64 y) { x ^= x ^ y; return x; } private static Int64 f99(Int64 x, Int64 y) { x ^= x | y; return x; } private static Int64 f100(Int64 x, Int64 y) { x |= x + y; return x; } private static Int64 f101(Int64 x, Int64 y) { x |= x - y; return x; } private static Int64 f102(Int64 x, Int64 y) { x |= x * y; return x; } private static Int64 f103(Int64 x, Int64 y) { x |= x / y; return x; } private static Int64 f104(Int64 x, Int64 y) { x |= x % y; return x; } private static Int64 f105(Int64 x, Int64 y) { x |= x << (int)y; return x; } private static Int64 f106(Int64 x, Int64 y) { x |= x >> (int)y; return x; } private static Int64 f107(Int64 x, Int64 y) { x |= x & y; return x; } private static Int64 f108(Int64 x, Int64 y) { x |= x ^ y; return x; } private static Int64 f109(Int64 x, Int64 y) { x |= x | y; return x; } public static int Main() { Int64 x; bool pass = true; x = f00(-10, 4); if (x != -6) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f00 x = x + y failed."); Console.WriteLine("x: {0}, \texpected: -6", x); pass = false; } x = f01(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f01 x = x - y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f02(-10, 4); if (x != -40) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f02 x = x * y failed."); Console.WriteLine("x: {0}, \texpected: -40", x); pass = false; } x = f03(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f03 x = x / y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f04(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f04 x = x % y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f05(-10, 4); if (x != -160) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f05 x = x << y failed."); Console.WriteLine("x: {0}, \texpected: -160", x); pass = false; } x = f06(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f06 x = x >> y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f07(-10, 4); if (x != 4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f07 x = x & y failed."); Console.WriteLine("x: {0}, \texpected: 4", x); pass = false; } x = f08(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f08 x = x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f09(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f09 x = x | y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f10(-10, 4); if (x != -16) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f10 x += x + y failed."); Console.WriteLine("x: {0}, \texpected: -16", x); pass = false; } x = f11(-10, 4); if (x != -24) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f11 x += x - y failed."); Console.WriteLine("x: {0}, \texpected: -24", x); pass = false; } x = f12(-10, 4); if (x != -50) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f12 x += x * y failed."); Console.WriteLine("x: {0}, \texpected: -50", x); pass = false; } x = f13(-10, 4); if (x != -12) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f13 x += x / y failed."); Console.WriteLine("x: {0}, \texpected: -12", x); pass = false; } x = f14(-10, 4); if (x != -12) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f14 x += x % y failed."); Console.WriteLine("x: {0}, \texpected: -12", x); pass = false; } x = f15(-10, 4); if (x != -170) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f15 x += x << y failed."); Console.WriteLine("x: {0}, \texpected: -170", x); pass = false; } x = f16(-10, 4); if (x != -11) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f16 x += x >> y failed."); Console.WriteLine("x: {0}, \texpected: -11", x); pass = false; } x = f17(-10, 4); if (x != -6) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f17 x += x & y failed."); Console.WriteLine("x: {0}, \texpected: -6", x); pass = false; } x = f18(-10, 4); if (x != -24) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f18 x += x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -24", x); pass = false; } x = f19(-10, 4); if (x != -20) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f19 x += x | y failed."); Console.WriteLine("x: {0}, \texpected: -20", x); pass = false; } x = f20(-10, 4); if (x != -4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f20 x -= x + y failed."); Console.WriteLine("x: {0}, \texpected: -4", x); pass = false; } x = f21(-10, 4); if (x != 4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f21 x -= x - y failed."); Console.WriteLine("x: {0}, \texpected: 4", x); pass = false; } x = f22(-10, 4); if (x != 30) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f22 x -= x * y failed."); Console.WriteLine("x: {0}, \texpected: 30", x); pass = false; } x = f23(-10, 4); if (x != -8) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f23 x -= x / y failed."); Console.WriteLine("x: {0}, \texpected: -8", x); pass = false; } x = f24(-10, 4); if (x != -8) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f24 x -= x % y failed."); Console.WriteLine("x: {0}, \texpected: -8", x); pass = false; } x = f25(-10, 4); if (x != 150) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f25 x -= x << y failed."); Console.WriteLine("x: {0}, \texpected: 150", x); pass = false; } x = f26(-10, 4); if (x != -9) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f26 x -= x >> y failed."); Console.WriteLine("x: {0}, \texpected: -9", x); pass = false; } x = f27(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f27 x -= x & y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f28(-10, 4); if (x != 4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f28 x -= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: 4", x); pass = false; } x = f29(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f29 x -= x | y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f30(-10, 4); if (x != 60) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f30 x *= x + y failed."); Console.WriteLine("x: {0}, \texpected: 60", x); pass = false; } x = f31(-10, 4); if (x != 140) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f31 x *= x - y failed."); Console.WriteLine("x: {0}, \texpected: 140", x); pass = false; } x = f32(-10, 4); if (x != 400) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f32 x *= x * y failed."); Console.WriteLine("x: {0}, \texpected: 400", x); pass = false; } x = f33(-10, 4); if (x != 20) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f33 x *= x / y failed."); Console.WriteLine("x: {0}, \texpected: 20", x); pass = false; } x = f34(-10, 4); if (x != 20) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f34 x *= x % y failed."); Console.WriteLine("x: {0}, \texpected: 20", x); pass = false; } x = f35(-10, 4); if (x != 1600) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f35 x *= x << y failed."); Console.WriteLine("x: {0}, \texpected: 1600", x); pass = false; } x = f36(-10, 4); if (x != 10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f36 x *= x >> y failed."); Console.WriteLine("x: {0}, \texpected: 10", x); pass = false; } x = f37(-10, 4); if (x != -40) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f37 x *= x & y failed."); Console.WriteLine("x: {0}, \texpected: -40", x); pass = false; } x = f38(-10, 4); if (x != 140) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f38 x *= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: 140", x); pass = false; } x = f39(-10, 4); if (x != 100) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f39 x *= x | y failed."); Console.WriteLine("x: {0}, \texpected: 100", x); pass = false; } x = f40(-10, 4); if (x != 1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f40 x /= x + y failed."); Console.WriteLine("x: {0}, \texpected: 1", x); pass = false; } x = f41(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f41 x /= x - y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f42(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f42 x /= x * y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f43(-10, 4); if (x != 5) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f43 x /= x / y failed."); Console.WriteLine("x: {0}, \texpected: 5", x); pass = false; } x = f44(-10, 4); if (x != 5) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f44 x /= x % y failed."); Console.WriteLine("x: {0}, \texpected: 5", x); pass = false; } x = f45(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f45 x /= x << y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f46(-10, 4); if (x != 10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f46 x /= x >> y failed."); Console.WriteLine("x: {0}, \texpected: 10", x); pass = false; } x = f47(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f47 x /= x & y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f48(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f48 x /= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f49(-10, 4); if (x != 1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f49 x /= x | y failed."); Console.WriteLine("x: {0}, \texpected: 1", x); pass = false; } x = f50(-10, 4); if (x != -4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f50 x %= x + y failed."); Console.WriteLine("x: {0}, \texpected: -4", x); pass = false; } x = f51(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f51 x %= x - y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f52(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f52 x %= x * y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f53(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f53 x %= x / y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f54(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f54 x %= x % y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f55(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f55 x %= x << y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f56(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f56 x %= x >> y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f57(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f57 x %= x & y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f58(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f58 x %= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f59(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f59 x %= x | y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } /* x = f60(-10, 4); if (x != -671088640) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f60 x <<= x + y failed."); Console.WriteLine("x: {0}, \texpected: -671088640", x); pass = false; } x = f61(-10, 4); if (x != -2621440) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f61 x <<= x - y failed."); Console.WriteLine("x: {0}, \texpected: -2621440", x); pass = false; } x = f62(-10, 4); if (x != -167772160) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f62 x <<= x * y failed."); Console.WriteLine("x: {0}, \texpected: -167772160", x); pass = false; } x = f63(-10, 4); if (x != -2147483648) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f63 x <<= x / y failed."); Console.WriteLine("x: {0}, \texpected: -2147483648", x); pass = false; } x = f64(-10, 4); if (x != -2147483648) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f64 x <<= x % y failed."); Console.WriteLine("x: {0}, \texpected: -2147483648", x); pass = false; } x = f65(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f65 x <<= x << y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } */ x = f66(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f66 x <<= x >> y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f67(-10, 4); if (x != -160) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f67 x <<= x & y failed."); Console.WriteLine("x: {0}, \texpected: -160", x); pass = false; } /* x = f68(-10, 4); if (x != -2621440) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f68 x <<= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -2621440", x); pass = false; } x = f69(-10, 4); if (x != -41943040) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f69 x <<= x | y failed."); Console.WriteLine("x: {0}, \texpected: -41943040", x); pass = false; } */ x = f70(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f70 x >>= x + y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f71(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f71 x >>= x - y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f72(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f72 x >>= x * y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f73(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f73 x >>= x / y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f74(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f74 x >>= x % y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } /* x = f75(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f75 x >>= x << y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } */ x = f76(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f76 x >>= x >> y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f77(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f77 x >>= x & y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f78(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f78 x >>= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f79(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f79 x >>= x | y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f80(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f80 x &= x + y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f81(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f81 x &= x - y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f82(-10, 4); if (x != -48) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f82 x &= x * y failed."); Console.WriteLine("x: {0}, \texpected: -48", x); pass = false; } x = f83(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f83 x &= x / y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f84(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f84 x &= x % y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f85(-10, 4); if (x != -160) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f85 x &= x << y failed."); Console.WriteLine("x: {0}, \texpected: -160", x); pass = false; } x = f86(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f86 x &= x >> y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f87(-10, 4); if (x != 4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f87 x &= x & y failed."); Console.WriteLine("x: {0}, \texpected: 4", x); pass = false; } x = f88(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f88 x &= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f89(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f89 x &= x | y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f90(-10, 4); if (x != 12) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f90 x ^= x + y failed."); Console.WriteLine("x: {0}, \texpected: 12", x); pass = false; } x = f91(-10, 4); if (x != 4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f91 x ^= x - y failed."); Console.WriteLine("x: {0}, \texpected: 4", x); pass = false; } x = f92(-10, 4); if (x != 46) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f92 x ^= x * y failed."); Console.WriteLine("x: {0}, \texpected: 46", x); pass = false; } x = f93(-10, 4); if (x != 8) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f93 x ^= x / y failed."); Console.WriteLine("x: {0}, \texpected: 8", x); pass = false; } x = f94(-10, 4); if (x != 8) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f94 x ^= x % y failed."); Console.WriteLine("x: {0}, \texpected: 8", x); pass = false; } x = f95(-10, 4); if (x != 150) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f95 x ^= x << y failed."); Console.WriteLine("x: {0}, \texpected: 150", x); pass = false; } x = f96(-10, 4); if (x != 9) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f96 x ^= x >> y failed."); Console.WriteLine("x: {0}, \texpected: 9", x); pass = false; } x = f97(-10, 4); if (x != -14) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f97 x ^= x & y failed."); Console.WriteLine("x: {0}, \texpected: -14", x); pass = false; } x = f98(-10, 4); if (x != 4) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f98 x ^= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: 4", x); pass = false; } x = f99(-10, 4); if (x != 0) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f99 x ^= x | y failed."); Console.WriteLine("x: {0}, \texpected: 0", x); pass = false; } x = f100(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f100 x |= x + y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f101(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f101 x |= x - y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f102(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f102 x |= x * y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f103(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f103 x |= x / y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f104(-10, 4); if (x != -2) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f104 x |= x % y failed."); Console.WriteLine("x: {0}, \texpected: -2", x); pass = false; } x = f105(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f105 x |= x << y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f106(-10, 4); if (x != -1) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f106 x |= x >> y failed."); Console.WriteLine("x: {0}, \texpected: -1", x); pass = false; } x = f107(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f107 x |= x & y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f108(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f108 x |= x ^ y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } x = f109(-10, 4); if (x != -10) { Console.WriteLine("\nInitial parameters: x is -10 and y is 4."); Console.WriteLine("f109 x |= x | y failed."); Console.WriteLine("x: {0}, \texpected: -10", x); pass = false; } if (pass) { Console.WriteLine("PASSED"); return 100; } else return 1; } }
25.482718
76
0.4413
[ "MIT" ]
belav/runtime
src/tests/JIT/Methodical/AsgOp/i8/i8.cs
42,760
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.MarketplaceEntitlementService")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Marketplace Entitlement Service. AWS Marketplace Entitlement Service enables AWS Marketplace sellers to determine the capacity purchased by their customers.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.100.108")]
48
240
0.759766
[ "Apache-2.0" ]
damianh/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/MarketplaceEntitlementService/Properties/AssemblyInfo.cs
1,536
C#
using System; using System.Collections.Generic; namespace NetworkProtocols { // Token: 0x0200059E RID: 1438 public class ContentDefinition { // Token: 0x060031DE RID: 12766 RVA: 0x0001AC49 File Offset: 0x00018E49 public ContentDefinition() { this.InitRefTypes(); } // Token: 0x170005B8 RID: 1464 // (get) Token: 0x060031DF RID: 12767 RVA: 0x0001AC57 File Offset: 0x00018E57 // (set) Token: 0x060031E0 RID: 12768 RVA: 0x0001AC5F File Offset: 0x00018E5F public ulong ContentDefinitionID { get; set; } // Token: 0x170005B9 RID: 1465 // (get) Token: 0x060031E1 RID: 12769 RVA: 0x0001AC68 File Offset: 0x00018E68 // (set) Token: 0x060031E2 RID: 12770 RVA: 0x0001AC70 File Offset: 0x00018E70 public eContentType ContentType { get; set; } // Token: 0x170005BA RID: 1466 // (get) Token: 0x060031E3 RID: 12771 RVA: 0x0001AC79 File Offset: 0x00018E79 // (set) Token: 0x060031E4 RID: 12772 RVA: 0x0001AC81 File Offset: 0x00018E81 public eContentSize ContentSize { get; set; } // Token: 0x170005BB RID: 1467 // (get) Token: 0x060031E5 RID: 12773 RVA: 0x0001AC8A File Offset: 0x00018E8A // (set) Token: 0x060031E6 RID: 12774 RVA: 0x0001AC92 File Offset: 0x00018E92 public eTabLink TabLink { get; set; } // Token: 0x170005BC RID: 1468 // (get) Token: 0x060031E7 RID: 12775 RVA: 0x0001AC9B File Offset: 0x00018E9B // (set) Token: 0x060031E8 RID: 12776 RVA: 0x0001ACA3 File Offset: 0x00018EA3 public bool UseLocalContent { get; set; } // Token: 0x170005BD RID: 1469 // (get) Token: 0x060031E9 RID: 12777 RVA: 0x0001ACAC File Offset: 0x00018EAC // (set) Token: 0x060031EA RID: 12778 RVA: 0x0001ACB4 File Offset: 0x00018EB4 public string PrimaryAsset { get; set; } // Token: 0x170005BE RID: 1470 // (get) Token: 0x060031EB RID: 12779 RVA: 0x0001ACBD File Offset: 0x00018EBD // (set) Token: 0x060031EC RID: 12780 RVA: 0x0001ACC5 File Offset: 0x00018EC5 public string PrimaryText { get; set; } // Token: 0x170005BF RID: 1471 // (get) Token: 0x060031ED RID: 12781 RVA: 0x0001ACCE File Offset: 0x00018ECE // (set) Token: 0x060031EE RID: 12782 RVA: 0x0001ACD6 File Offset: 0x00018ED6 public string SecondaryText { get; set; } // Token: 0x170005C0 RID: 1472 // (get) Token: 0x060031EF RID: 12783 RVA: 0x0001ACDF File Offset: 0x00018EDF // (set) Token: 0x060031F0 RID: 12784 RVA: 0x0001ACE7 File Offset: 0x00018EE7 public string TargetAsset { get; set; } // Token: 0x170005C1 RID: 1473 // (get) Token: 0x060031F1 RID: 12785 RVA: 0x0001ACF0 File Offset: 0x00018EF0 // (set) Token: 0x060031F2 RID: 12786 RVA: 0x0001ACF8 File Offset: 0x00018EF8 public ulong OfferID { get; set; } // Token: 0x170005C2 RID: 1474 // (get) Token: 0x060031F3 RID: 12787 RVA: 0x0001AD01 File Offset: 0x00018F01 // (set) Token: 0x060031F4 RID: 12788 RVA: 0x0001AD09 File Offset: 0x00018F09 public uint QuestCurrent { get; set; } // Token: 0x170005C3 RID: 1475 // (get) Token: 0x060031F5 RID: 12789 RVA: 0x0001AD12 File Offset: 0x00018F12 // (set) Token: 0x060031F6 RID: 12790 RVA: 0x0001AD1A File Offset: 0x00018F1A public uint QuestMax { get; set; } // Token: 0x170005C4 RID: 1476 // (get) Token: 0x060031F7 RID: 12791 RVA: 0x0001AD23 File Offset: 0x00018F23 // (set) Token: 0x060031F8 RID: 12792 RVA: 0x0001AD2B File Offset: 0x00018F2B public List<string> URLTexts { get; set; } // Token: 0x170005C5 RID: 1477 // (get) Token: 0x060031F9 RID: 12793 RVA: 0x0001AD34 File Offset: 0x00018F34 // (set) Token: 0x060031FA RID: 12794 RVA: 0x0001AD3C File Offset: 0x00018F3C public List<string> URLImages { get; set; } // Token: 0x170005C6 RID: 1478 // (get) Token: 0x060031FB RID: 12795 RVA: 0x0001AD45 File Offset: 0x00018F45 // (set) Token: 0x060031FC RID: 12796 RVA: 0x0001AD4D File Offset: 0x00018F4D public List<string> TargetURLs { get; set; } // Token: 0x060031FD RID: 12797 RVA: 0x00104618 File Offset: 0x00102818 public byte[] SerializeMessage() { byte[] newArray = ArrayManager.GetNewArray(); int newSize = 0; ArrayManager.WriteUInt64(ref newArray, ref newSize, this.ContentDefinitionID); ArrayManager.WriteeContentType(ref newArray, ref newSize, this.ContentType); ArrayManager.WriteeContentSize(ref newArray, ref newSize, this.ContentSize); ArrayManager.WriteeTabLink(ref newArray, ref newSize, this.TabLink); ArrayManager.WriteBoolean(ref newArray, ref newSize, this.UseLocalContent); ArrayManager.WriteString(ref newArray, ref newSize, this.PrimaryAsset); ArrayManager.WriteString(ref newArray, ref newSize, this.PrimaryText); ArrayManager.WriteString(ref newArray, ref newSize, this.SecondaryText); ArrayManager.WriteString(ref newArray, ref newSize, this.TargetAsset); ArrayManager.WriteUInt64(ref newArray, ref newSize, this.OfferID); ArrayManager.WriteUInt32(ref newArray, ref newSize, this.QuestCurrent); ArrayManager.WriteUInt32(ref newArray, ref newSize, this.QuestMax); ArrayManager.WriteListString(ref newArray, ref newSize, this.URLTexts); ArrayManager.WriteListString(ref newArray, ref newSize, this.URLImages); ArrayManager.WriteListString(ref newArray, ref newSize, this.TargetURLs); Array.Resize<byte>(ref newArray, newSize); return newArray; } // Token: 0x060031FE RID: 12798 RVA: 0x00104718 File Offset: 0x00102918 public void DeserializeMessage(byte[] data) { int num = 0; this.ContentDefinitionID = ArrayManager.ReadUInt64(data, ref num); this.ContentType = ArrayManager.ReadeContentType(data, ref num); this.ContentSize = ArrayManager.ReadeContentSize(data, ref num); this.TabLink = ArrayManager.ReadeTabLink(data, ref num); this.UseLocalContent = ArrayManager.ReadBoolean(data, ref num); this.PrimaryAsset = ArrayManager.ReadString(data, ref num); this.PrimaryText = ArrayManager.ReadString(data, ref num); this.SecondaryText = ArrayManager.ReadString(data, ref num); this.TargetAsset = ArrayManager.ReadString(data, ref num); this.OfferID = ArrayManager.ReadUInt64(data, ref num); this.QuestCurrent = ArrayManager.ReadUInt32(data, ref num); this.QuestMax = ArrayManager.ReadUInt32(data, ref num); this.URLTexts = ArrayManager.ReadListString(data, ref num); this.URLImages = ArrayManager.ReadListString(data, ref num); this.TargetURLs = ArrayManager.ReadListString(data, ref num); } // Token: 0x060031FF RID: 12799 RVA: 0x001047FC File Offset: 0x001029FC private void InitRefTypes() { this.ContentDefinitionID = 0UL; this.ContentType = eContentType.TextBlock; this.ContentSize = eContentSize.Small; this.TabLink = eTabLink.None; this.UseLocalContent = false; this.PrimaryAsset = string.Empty; this.PrimaryText = string.Empty; this.SecondaryText = string.Empty; this.TargetAsset = string.Empty; this.OfferID = 0UL; this.QuestCurrent = 0u; this.QuestMax = 0u; this.URLTexts = new List<string>(); this.URLImages = new List<string>(); this.TargetURLs = new List<string>(); } } }
45.74359
82
0.71875
[ "Unlicense" ]
PermaNulled/OMDUC_EMU_CSharp
OMDUC_EMU/NetworkProtocols/ContentDefinition.cs
7,138
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the logs-2014-03-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudWatchLogs.Model { /// <summary> /// Container for the parameters to the DisassociateKmsKey operation. /// Disassociates the associated AWS Key Management Service (AWS KMS) customer master /// key (CMK) from the specified log group. /// /// /// <para> /// After the AWS KMS CMK is disassociated from the log group, AWS CloudWatch Logs stops /// encrypting newly ingested data for the log group. All previously ingested data remains /// encrypted, and AWS CloudWatch Logs requires permissions for the CMK whenever the encrypted /// data is requested. /// </para> /// /// <para> /// Note that it can take up to 5 minutes for this operation to take effect. /// </para> /// </summary> public partial class DisassociateKmsKeyRequest : AmazonCloudWatchLogsRequest { private string _logGroupName; /// <summary> /// Gets and sets the property LogGroupName. /// <para> /// The name of the log group. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=512)] public string LogGroupName { get { return this._logGroupName; } set { this._logGroupName = value; } } // Check to see if LogGroupName property is set internal bool IsSetLogGroupName() { return this._logGroupName != null; } } }
32.746479
102
0.658495
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/CloudWatchLogs/Generated/Model/DisassociateKmsKeyRequest.cs
2,325
C#
// Copyright 2020 Greg Eakin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SUBSYSTEM: ShoppingCart // FILE: IEventStore.cs // AUTHOR: Greg Eakin using System.Collections.Generic; namespace ShoppingCartSvc.EventFeed { public interface IEventStore { IEnumerable<Event> GetEvents(ulong firstEventSequenceNumber, ulong lastEventSequenceNumber); ulong Raise(string eventName, object content); } }
34.851852
100
0.742827
[ "Apache-2.0" ]
GregEakin/Microservices
ShoppingCartSvc/EventFeed/IEventStore.cs
943
C#
using CustomerInviter.Entities; using System.Collections.Generic; namespace CustomerInviter.Abstractions { public interface ICustomerFinder { IEnumerable<Customer> Find(Configuration configuration); } }
22.4
64
0.767857
[ "MIT" ]
tugrulelmas/CustomerInviter
src/CustomerInviter/Abstractions/ICustomerFinder.cs
226
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Microsoft.ML.Runtime.Internal.Utilities; namespace Microsoft.ML.Runtime.EntryPoints { /// <summary> /// This is a signature for classes that are 'holders' of entry points and components. /// </summary> public delegate void SignatureEntryPointModule(); /// <summary> /// A simplified assembly attribute for marking EntryPoint modules. /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class EntryPointModuleAttribute : LoadableClassAttributeBase { public EntryPointModuleAttribute(Type loaderType) : base(null, typeof(void), loaderType, null, new[] { typeof(SignatureEntryPointModule) }, loaderType.FullName) { } } /// <summary> /// This is a class that contains all entry point and component declarations. /// REVIEW: it looks like a good idea to actually make <see cref="ModuleCatalog"/> a part of <see cref="IHostEnvironment"/>. Currently, this is not the case, /// but this is the plan. /// </summary> public sealed class ModuleCatalog { /// <summary> /// A description of a single entry point. /// </summary> public sealed class EntryPointInfo { public readonly string Name; public readonly string Description; public readonly string ShortName; public readonly string FriendlyName; public readonly MethodInfo Method; public readonly Type InputType; public readonly Type OutputType; public readonly Type[] InputKinds; public readonly Type[] OutputKinds; public readonly ObsoleteAttribute ObsoleteAttribute; internal EntryPointInfo(IExceptionContext ectx, MethodInfo method, TlcModule.EntryPointAttribute attribute, ObsoleteAttribute obsoleteAttribute) { Contracts.AssertValueOrNull(ectx); ectx.AssertValue(method); ectx.AssertValue(attribute); Name = attribute.Name ?? string.Join(".", method.DeclaringType.Name, method.Name); Description = attribute.Desc; Method = method; ShortName = attribute.ShortName; FriendlyName = attribute.UserName; ObsoleteAttribute = obsoleteAttribute; // There are supposed to be 2 parameters, env and input for non-macro nodes. // Macro nodes have a 3rd parameter, the entry point node. var parameters = method.GetParameters(); if (parameters.Length != 2 && parameters.Length != 3) throw ectx.Except("Method '{0}' has {1} parameters, but must have 2 or 3", method.Name, parameters.Length); if (parameters[0].ParameterType != typeof(IHostEnvironment)) throw ectx.Except("Method '{0}', 1st parameter is {1}, but must be IHostEnvironment", method.Name, parameters[0].ParameterType); InputType = parameters[1].ParameterType; var outputType = method.ReturnType; if (!outputType.IsClass) throw ectx.Except("Method '{0}' returns {1}, but must return a class", method.Name, outputType); OutputType = outputType; InputKinds = FindEntryPointKinds(InputType); OutputKinds = FindEntryPointKinds(OutputType); } private Type[] FindEntryPointKinds(Type type) { var kindAttr = type.GetTypeInfo().GetCustomAttributes(typeof(TlcModule.EntryPointKindAttribute), false).FirstOrDefault() as TlcModule.EntryPointKindAttribute; var baseType = type.BaseType; if (baseType == null) return kindAttr?.Kinds; var baseKinds = FindEntryPointKinds(baseType); if (kindAttr == null) return baseKinds; if (baseKinds == null) return kindAttr.Kinds; return kindAttr.Kinds.Concat(baseKinds).ToArray(); } public override string ToString() => $"{Name}: {Description}"; } /// <summary> /// A description of a single component. /// The 'component' is a non-standalone building block that is used to parametrize entry points or other TLC components. /// For example, 'Loss function', or 'similarity calculator' could be components. /// </summary> public sealed class ComponentInfo { public readonly string Name; public readonly string Description; public readonly string FriendlyName; public readonly string Kind; public readonly Type ArgumentType; public readonly Type InterfaceType; public readonly string[] Aliases; internal ComponentInfo(IExceptionContext ectx, Type interfaceType, string kind, Type argumentType, TlcModule.ComponentAttribute attribute) { Contracts.AssertValueOrNull(ectx); ectx.AssertValue(interfaceType); ectx.AssertNonEmpty(kind); ectx.AssertValue(argumentType); ectx.AssertValue(attribute); Name = attribute.Name; Description = attribute.Desc; if (string.IsNullOrWhiteSpace(attribute.FriendlyName)) FriendlyName = Name; else FriendlyName = attribute.FriendlyName; Kind = kind; if (!IsValidName(Kind)) throw ectx.Except("Invalid component kind: '{0}'", Kind); Aliases = attribute.Aliases; if (!IsValidName(Name)) throw ectx.Except("Component name '{0}' is not valid.", Name); if (Aliases != null && Aliases.Any(x => !IsValidName(x))) throw ectx.Except("Component '{0}' has an invalid alias '{1}'", Name, Aliases.First(x => !IsValidName(x))); if (!typeof(IComponentFactory).IsAssignableFrom(argumentType)) throw ectx.Except("Component '{0}' must inherit from IComponentFactory", argumentType); ArgumentType = argumentType; InterfaceType = interfaceType; } } private static volatile ModuleCatalog _instance; private readonly EntryPointInfo[] _entryPoints; private readonly Dictionary<string, EntryPointInfo> _entryPointMap; private readonly List<ComponentInfo> _components; private readonly Dictionary<string, ComponentInfo> _componentMap; /// <summary> /// Get all registered entry points. /// </summary> public IEnumerable<EntryPointInfo> AllEntryPoints() { return _entryPoints.AsEnumerable(); } private ModuleCatalog(IExceptionContext ectx) { Contracts.AssertValue(ectx); _entryPointMap = new Dictionary<string, EntryPointInfo>(); _componentMap = new Dictionary<string, ComponentInfo>(); _components = new List<ComponentInfo>(); var moduleClasses = ComponentCatalog.FindLoadableClasses<SignatureEntryPointModule>(); var entryPoints = new List<EntryPointInfo>(); foreach (var lc in moduleClasses) { var type = lc.LoaderType; // Scan for entry points. foreach (var methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) { var attr = methodInfo.GetCustomAttributes(typeof(TlcModule.EntryPointAttribute), false).FirstOrDefault() as TlcModule.EntryPointAttribute; if (attr == null) continue; var info = new EntryPointInfo(ectx, methodInfo, attr, methodInfo.GetCustomAttributes(typeof(ObsoleteAttribute), false).FirstOrDefault() as ObsoleteAttribute); entryPoints.Add(info); if (_entryPointMap.ContainsKey(info.Name)) { // Duplicate entry point name. We need to show a warning here. // REVIEW: we will be able to do this once catalog becomes a part of env. continue; } _entryPointMap[info.Name] = info; } // Scan for components. // First scan ourself, and then all nested types, for component info. ScanForComponents(ectx, type); foreach (var nestedType in type.GetTypeInfo().GetNestedTypes()) ScanForComponents(ectx, nestedType); } _entryPoints = entryPoints.ToArray(); } private bool ScanForComponents(IExceptionContext ectx, Type nestedType) { var attr = nestedType.GetTypeInfo().GetCustomAttributes(typeof(TlcModule.ComponentAttribute), true).FirstOrDefault() as TlcModule.ComponentAttribute; if (attr == null) return false; bool found = false; foreach (var faceType in nestedType.GetInterfaces()) { var faceAttr = faceType.GetTypeInfo().GetCustomAttributes(typeof(TlcModule.ComponentKindAttribute), false).FirstOrDefault() as TlcModule.ComponentKindAttribute; if (faceAttr == null) continue; if (!typeof(IComponentFactory).IsAssignableFrom(faceType)) throw ectx.Except("Component signature '{0}' doesn't inherit from '{1}'", faceType, typeof(IComponentFactory)); try { // In order to populate from JSON, we need to invoke the parameterless ctor. Testing that this is possible. Activator.CreateInstance(nestedType); } catch (MissingMemberException ex) { throw ectx.Except(ex, "Component type '{0}' doesn't have a default constructor", faceType); } var info = new ComponentInfo(ectx, faceType, faceAttr.Kind, nestedType, attr); var names = (info.Aliases ?? new string[0]).Concat(new[] { info.Name }).Distinct(); _components.Add(info); foreach (var alias in names) { var tag = $"{info.Kind}:{alias}"; if (_componentMap.ContainsKey(tag)) { // Duplicate component name. We need to show a warning here. // REVIEW: we will be able to do this once catalog becomes a part of env. continue; } _componentMap[tag] = info; } } return found; } /// <summary> /// The valid names for the components and entry points must consist of letters, digits, underscores and dots, /// and begin with a letter or digit. /// </summary> private static readonly Regex _nameRegex = new Regex(@"^\w[_\.\w]*$", RegexOptions.Compiled); private static bool IsValidName(string name) { Contracts.AssertValueOrNull(name); if (string.IsNullOrWhiteSpace(name)) return false; return _nameRegex.IsMatch(name); } /// <summary> /// Create a module catalog (or reuse the one created before). /// </summary> /// <param name="ectx">The exception context to use to report errors while scanning the assemblies.</param> public static ModuleCatalog CreateInstance(IExceptionContext ectx) { Contracts.CheckValueOrNull(ectx); #pragma warning disable 420 // volatile with Interlocked.CompareExchange. if (_instance == null) Interlocked.CompareExchange(ref _instance, new ModuleCatalog(ectx), null); #pragma warning restore 420 return _instance; } public bool TryFindEntryPoint(string name, out EntryPointInfo entryPoint) { Contracts.CheckNonEmpty(name, nameof(name)); return _entryPointMap.TryGetValue(name, out entryPoint); } public bool TryFindComponent(string kind, string alias, out ComponentInfo component) { Contracts.CheckNonEmpty(kind, nameof(kind)); Contracts.CheckNonEmpty(alias, nameof(alias)); // Note that, if kind or alias contain the colon character, the kind:name 'tag' will contain more than one colon. // Since colon may not appear in any valid name, the dictionary lookup is guaranteed to fail. return _componentMap.TryGetValue($"{kind}:{alias}", out component); } public bool TryFindComponent(Type argumentType, out ComponentInfo component) { Contracts.CheckValue(argumentType, nameof(argumentType)); component = _components.FirstOrDefault(x => x.ArgumentType == argumentType); return component != null; } public bool TryFindComponent(Type interfaceType, Type argumentType, out ComponentInfo component) { Contracts.CheckValue(interfaceType, nameof(interfaceType)); Contracts.CheckParam(interfaceType.IsInterface, nameof(interfaceType), "Must be interface"); Contracts.CheckValue(argumentType, nameof(argumentType)); component = _components.FirstOrDefault(x => x.InterfaceType == interfaceType && x.ArgumentType == argumentType); return component != null; } public bool TryFindComponent(Type interfaceType, string alias, out ComponentInfo component) { Contracts.CheckValue(interfaceType, nameof(interfaceType)); Contracts.CheckParam(interfaceType.IsInterface, nameof(interfaceType), "Must be interface"); Contracts.CheckNonEmpty(alias, nameof(alias)); component = _components.FirstOrDefault(x => x.InterfaceType == interfaceType && (x.Name == alias || (x.Aliases != null && x.Aliases.Contains(alias)))); return component != null; } /// <summary> /// Akin to <see cref="TryFindComponent(Type, string, out ComponentInfo)"/>, except if the regular (case sensitive) comparison fails, it will /// attempt to back off to a case-insensitive comparison. /// </summary> public bool TryFindComponentCaseInsensitive(Type interfaceType, string alias, out ComponentInfo component) { Contracts.CheckValue(interfaceType, nameof(interfaceType)); Contracts.CheckParam(interfaceType.IsInterface, nameof(interfaceType), "Must be interface"); Contracts.CheckNonEmpty(alias, nameof(alias)); if (TryFindComponent(interfaceType, alias, out component)) return true; alias = alias.ToLowerInvariant(); component = _components.FirstOrDefault(x => x.InterfaceType == interfaceType && (x.Name.ToLowerInvariant() == alias || AnyMatch(alias, x.Aliases))); return component != null; } private static bool AnyMatch(string name, string[] aliases) { if (aliases == null) return false; return aliases.Any(a => string.Equals(name, a, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Returns all valid component kinds. /// </summary> public IEnumerable<string> GetAllComponentKinds() { return _components.Select(x => x.Kind).Distinct().OrderBy(x => x); } /// <summary> /// Returns all components of the specified kind. /// </summary> public IEnumerable<ComponentInfo> GetAllComponents(string kind) { Contracts.CheckNonEmpty(kind, nameof(kind)); Contracts.CheckParam(IsValidName(kind), nameof(kind), "Invalid component kind"); return _components.Where(x => x.Kind == kind).OrderBy(x => x.Name); } /// <summary> /// Returns all components that implement the specified interface. /// </summary> public IEnumerable<ComponentInfo> GetAllComponents(Type interfaceType) { Contracts.CheckValue(interfaceType, nameof(interfaceType)); return _components.Where(x => x.InterfaceType == interfaceType).OrderBy(x => x.Name); } public bool TryGetComponentKind(Type signatureType, out string kind) { Contracts.CheckValue(signatureType, nameof(signatureType)); // REVIEW: replace with a dictionary lookup. var faceAttr = signatureType.GetTypeInfo().GetCustomAttributes(typeof(TlcModule.ComponentKindAttribute), false).FirstOrDefault() as TlcModule.ComponentKindAttribute; kind = faceAttr == null ? null : faceAttr.Kind; return faceAttr != null; } public bool TryGetComponentShortName(Type type, out string name) { ComponentInfo component; if (!TryFindComponent(type, out component)) { name = null; return false; } name = component.Aliases != null && component.Aliases.Length > 0 ? component.Aliases[0] : component.Name; return true; } } }
44.566502
163
0.598541
[ "MIT" ]
CrystalWindSnake/machinelearning
src/Microsoft.ML.Core/EntryPoints/ModuleCatalog.cs
18,094
C#
namespace TicTacToe.Logic { public enum PlayerMarker { X, O, Tie } }
11.666667
28
0.47619
[ "MIT" ]
danabarz/TicTacToe
TicTacToe/Logic/PlayerMarker.cs
107
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; namespace QuantConnect.Algorithm.Examples { /// <summary> /// Example algorithm giving an introduction into using IDataConsolidators. /// /// This is an advanced QC concept and requires a certain level of comfort using C# and its event system. /// /// What is an IDataConsolidator? /// IDataConsolidator is a plugin point that can be used to transform your data more easily. /// In this example we show one of the simplest consolidators, the TradeBarConsolidator. /// This type is capable of taking a timespan to indicate how long each bar should be, or an /// integer to indicate how many bars should be aggregated into one. /// /// When a new 'consolidated' piece of data is produced by the IDataConsolidator, an event is fired /// with the argument of the new data. /// /// If you are unfamiliar with C# events, or events in general, you may find this useful. This is /// Microsoft's overview of events in C# /// /// http://msdn.microsoft.com/en-us/library/aa645739%28v=vs.71%29.aspx /// /// Also, if you're unfamiliar with using lambda expressions in C#, you may find this useful. This /// is Microsoft's overview of lambda expressions in C# (anonymous functions) /// /// http://msdn.microsoft.com/en-us/library/bb397687.aspx /// /// </summary> public class DataConsolidationAlgorithm : QCAlgorithm { TradeBar _last; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { AddSecurity(SecurityType.Equity, "SPY"); // we have data for these dates locally var start = new DateTime(2013, 10, 07, 09, 30, 0); SetStartDate(start); SetEndDate(start.AddDays(1)); // define our 30 minute trade bar consolidator. we can access the 30 minute bar // from the DataConsolidated events var thirtyMinuteConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(30)); // attach our event handler. the event handler is a function that will be called each time we produce // a new consolidated piece of data. thirtyMinuteConsolidator.DataConsolidated += ThirtyMinuteBarHandler; // this call adds our 30 minute consolidator to the manager to receive updates from the engine SubscriptionManager.AddConsolidator("SPY", thirtyMinuteConsolidator); // here we'll define a slightly more complex consolidator. what we're trying to produce is a 3 // day bar. Now we could just use a single TradeBarConsolidator like above and pass in TimeSpan.FromDays(3), // but in reality that's not what we want. For time spans of longer than a day we'll get incorrect results around // weekends and such. What we really want are tradeable days. So we'll create a daily consolidator, and then wrap // it with a 3 count consolidator. // first define a one day trade bar -- this produces a consolidated piece of data after a day has passed var oneDayConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1)); // next define our 3 count trade bar -- this produces a consolidated piece of data after it sees 3 pieces of data var threeCountConsolidator = new TradeBarConsolidator(3); // here we combine them to make a new, 3 day trade bar. The SequentialConsolidator allows composition of consolidators. // it takes the consolidated output of one consolidator (in this case, the oneDayConsolidator) and pipes it through to // the threeCountConsolidator. His output will be a 3 day bar. var three_oneDayBar = new SequentialConsolidator(oneDayConsolidator, threeCountConsolidator); // attach our handler three_oneDayBar.DataConsolidated += (sender, consolidated) => ThreeDayBarConsolidatedHandler(sender, (TradeBar) consolidated); // this call adds our 3 day to the manager to receive updates from the engine SubscriptionManager.AddConsolidator("SPY", three_oneDayBar); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="bars">TradeBars IDictionary object with your stock data</param> public void OnData(TradeBars bars) { // we need to declare this method } /// <summary> /// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets). /// </summary> /// <param name="symbol">Asset symbol for this end of day event. Forex and equities have different closing hours.</param> public override void OnEndOfDay(string symbol) { // close up shop each day and reset our 'last' value so we start tomorrow fresh Liquidate(symbol); _last = null; } /// <summary> /// This is our event handler for our 30 minute trade bar defined above in Initialize(). So each time the consolidator /// produces a new 30 minute bar, this function will be called automatically. The 'sender' parameter will be the /// instance of the IDataConsolidator that invoked the event, but you'll almost never need that! /// </summary> private void ThirtyMinuteBarHandler(object sender, TradeBar consolidated) { if (_last != null && consolidated.Close > _last.Close) { Log(consolidated.Time.ToString("o") + " >> SPY >> LONG >> 100 >> " + Portfolio["SPY"].Quantity); Order("SPY", 100); } else if (_last != null && consolidated.Close < _last.Close) { Log(consolidated.Time.ToString("o") + " >> SPY >> SHORT >> 100 >> " + Portfolio["SPY"].Quantity); Order("SPY", -100); } _last = consolidated; } /// <summary> /// This is our event handler for our 3 day trade bar defined above in Initialize(). So each time the consolidator /// produces a new 3 day bar, this function will be called automatically. The 'sender' parameter will be the /// instance of the IDataConsolidator that invoked the event, but you'll almost never need that! /// </summary> private void ThreeDayBarConsolidatedHandler(object sender, TradeBar consolidated) { Log(consolidated.Time.ToString("0") + " >> Plotting!"); Plot(consolidated.Symbol, "3HourBar", consolidated.Close); } } }
51.251656
149
0.656286
[ "Apache-2.0" ]
CircleOnCircles/Lean
Algorithm.CSharp/DataConsolidationAlgorithm.cs
7,741
C#
using Quantumart.QP8.BLL.Services.ArticleServices; using Quantumart.QP8.BLL.Services.DTO; using Quantumart.QP8.BLL.Services.MultistepActions.Base; namespace Quantumart.QP8.BLL.Services.MultistepActions.Archive { public class ArchiveArticlesCommand : MultistepActionStageCommandBase { protected override MessageResult Step(int[] ids) => ArticleService.MultistepMoveToArchive(ContentId, ids, BoundToExternal); } }
36.083333
131
0.803695
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
QuantumArt/QP
bll/Services/MultistepActions/Archive/ArchiveArticlesCommand.cs
433
C#
using System.Collections.Generic; using System.Linq; using ICSharpCode.CodeConverter.CSharp; using Xunit; using System.IO; using System.Threading.Tasks; using ICSharpCode.CodeConverter.Tests.TestRunners; using ICSharpCode.CodeConverter.Shared; namespace ICSharpCode.CodeConverter.Tests.CSharp { /// <summary> /// Run pairs of xUnit tests in converted code before and after conversion /// to verify code conversion did not break the tests. /// </summary> public class SelfVerifyingTests { [Theory, MemberData(nameof(GetVisualBasicToCSharpTestData))] public async Task VisualBasicToCSharpAsync(NamedTest verifyConvertedTestPasses) { await verifyConvertedTestPasses.Execute(); } /// <summary> /// Compile VB.NET source, convert it to C#, compile the conversion /// and return actions which run each corresponding pair of tests. /// </summary> public static IEnumerable<object[]> GetVisualBasicToCSharpTestData() { var testFiles = Directory.GetFiles(Path.Combine(TestConstants.GetTestDataDirectory(), "SelfVerifyingTests/VBToCS"), "*.vb"); return testFiles.SelectMany(SelfVerifyingTestFactory.GetSelfVerifyingFacts<VisualBasicCompiler, CSharpCompiler, VBToCSConversion>) .Select(et => new object[] {et}) .ToArray(); } } }
38.945946
143
0.676613
[ "MIT" ]
jrmoreno1/CodeConverter
Tests/CSharp/SelfVerifyingTests.cs
1,407
C#
using Android.App; using Android.Runtime; namespace BorderDemo; [Application] public class MainApplication : MauiApplication { public MainApplication(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership) { } protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); }
19.5
75
0.785256
[ "MIT" ]
davidbritch/dotnet-maui-samples
UserInterface/Views/BorderDemo/BorderDemo/Platforms/Android/MainApplication.cs
314
C#
using DragonSpark.Model.Results; using DragonSpark.Runtime.Activation; using System; namespace DragonSpark.Model.Commands; public class DelegatedInstanceCommand : DelegatedInstanceCommand<None>, ICommand { public DelegatedInstanceCommand(IResult<ICommand> result) : base(result) {} public DelegatedInstanceCommand(Func<ICommand> instance) : base(instance) {} } public class DelegatedInstanceCommand<T> : ICommand<T>, IActivateUsing<IResult<ICommand<T>>> { readonly Func<ICommand<T>> _instance; public DelegatedInstanceCommand(IResult<ICommand<T>> result) : this(result.Get) {} public DelegatedInstanceCommand(Func<ICommand<T>> instance) => _instance = instance; public void Execute(T parameter) => _instance().Execute(parameter); }
31.083333
92
0.789544
[ "MIT" ]
DragonSpark/Framework
DragonSpark/Model/Commands/DelegatedInstanceCommand.cs
748
C#
using System.Collections.Generic; namespace Sdk4me { public class RequestTemplateHandler : BaseHandler<RequestTemplate, PredefinedRequestTemplateFilter> { public RequestTemplateHandler(AuthenticationToken authenticationToken, string accountID = null, EnvironmentType environmentType = EnvironmentType.Production, int itemsPerRequest = 100, int maximumRecursiveRequests = 50) : base($"{Common.GetBaseUrl(environmentType)}/v1/request_templates", authenticationToken, accountID, itemsPerRequest, maximumRecursiveRequests) { } public RequestTemplateHandler(AuthenticationTokenCollection authenticationTokens, string accountID = null, EnvironmentType environmentType = EnvironmentType.Production, int itemsPerRequest = 100, int maximumRecursiveRequests = 50) : base($"{Common.GetBaseUrl(environmentType)}/v1/request_templates", authenticationTokens, accountID, itemsPerRequest, maximumRecursiveRequests) { } #region requests public List<Request> GetRequests(RequestTemplate requestTemplate, params string[] attributeNames) { DefaultHandler<Request> handler = new DefaultHandler<Request>($"{URL}/{requestTemplate.ID}/requests", this.AuthenticationTokens, this.AccountID, this.ItemsPerRequest, this.MaximumRecursiveRequests); return handler.Get(attributeNames); } #endregion } }
51
240
0.748599
[ "MIT" ]
code4me/4me-sdk-csharp
Source/Sdk4me/Handlers/RequestTemplateHandler.cs
1,430
C#
using OOM.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOM.Core.Analyzers { public abstract class CodeAnalyzer : IDisposable { #region Properties protected CodeAnalyzerConfiguration Configuration { get; private set; } #endregion #region Ctor public CodeAnalyzer(CodeAnalyzerConfiguration configuration) { Configuration = configuration; } #endregion #region Methods public abstract IEnumerable<Namespace> Analyze(string code); #endregion #region Privates public virtual void Dispose() { } #endregion } }
17.604651
79
0.635403
[ "MIT" ]
luanmm/OO-Metrics
OOM.Core/Analyzers/CodeAnalyzer.cs
759
C#
using System; using System.Collections.Generic; namespace Suzianna.Reporting.XmlNodes { public class ScenarioNode { public string Title { get; set; } public ScenarioStatus Status { get; set; } public DateTime? Start { get; set; } public DateTime? End { get; set; } public TimeSpan? Duration { get; set; } public string FailureReason { get; set; } public List<StepNode> Steps { get; set; } public ScenarioNode() { this.Steps = new List<StepNode>(); } internal void MarkAsPassed(DateTime date) { this.Status = ScenarioStatus.Passed; SetEnd(date); } internal void MarkAsFailed(string reason, DateTime date) { this.Status = ScenarioStatus.Failed; this.FailureReason = reason; SetEnd(date); } private void SetEnd(DateTime date) { this.End = date; if (this.Start != null) this.Duration = this.End - this.Start; } } }
27.948718
64
0.550459
[ "Apache-2.0" ]
H-Ahmadi/Suzianna
Code/src/Suzianna.Reporting/XmlNodes/ScenarioNode.cs
1,092
C#
namespace OnlineBookStoreDemo.Data { using System.IO; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Configuration; public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<BookStoreDbContext> { public BookStoreDbContext CreateDbContext(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var builder = new DbContextOptionsBuilder<BookStoreDbContext>(); var connectionString = configuration.GetConnectionString("DefaultConnection"); builder.UseSqlServer(connectionString); // Stop client query evaluation builder.ConfigureWarnings(w => w.Throw(RelationalEventId.QueryClientEvaluationWarning)); return new BookStoreDbContext(builder.Options); } } }
34.59375
100
0.693767
[ "MIT" ]
Pivchev/OnlineBookStoreDemo
src/Data/OnlineBookStoreDemo.Data/DesignTimeDbContextFactory.cs
1,109
C#
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System.ComponentModel.DataAnnotations; namespace Piranha.Models { /// <summary> /// Base class for templated content types. /// </summary> [Serializable] public abstract class ContentTypeBase : ITypeModel { /// <summary> /// Gets/sets the unique id. /// </summary> [Required] [StringLength(64)] public string Id { get; set; } /// <summary> /// Gets/sets the CLR type of the content model. /// </summary> [StringLength(255)] public string CLRType { get; set; } /// <summary> /// Gets/sets the optional title. /// </summary> public string Title { get; set; } /// <summary> /// Gets/sets the optional description. /// </summary> public string Description { get; set; } /// <summary> /// Gets/sets the available regions. /// </summary> public IList<ContentTypeRegion> Regions { get; set; } = new List<ContentTypeRegion>(); /// <summary> /// Gets/sets the optional routes. /// </summary> public IList<ContentTypeRoute> Routes { get; set; } = new List<ContentTypeRoute>(); /// <summary> /// Gets/sets the optional custom editors. /// </summary> public IList<ContentTypeEditor> CustomEditors { get; set; } = new List<ContentTypeEditor>(); } }
28.666667
101
0.554651
[ "MIT" ]
AllPIM/RhHERO-Web
core/Piranha/Models/ContentTypeBase.cs
1,722
C#
// InRoomRewards Decompiled was cancelled.
11
25
0.795455
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin.Net.Offline/InRoomRewards.cs
44
C#
using System.Runtime.InteropServices; using System.Collections.Generic; using UnityEngine.InputSystem.Utilities; using UnityEngine.InputSystem.LowLevel; namespace UnityEngine.InputSystem.XR.Haptics { [StructLayout(LayoutKind.Explicit, Size = kSize)] public unsafe struct SendBufferedHapticCommand : IInputDeviceCommandInfo { static FourCC Type { get { return new FourCC('X', 'H', 'U', '0'); } } const int kMaxHapticBufferSize = 1024; const int kSize = InputDeviceCommand.kBaseCommandSize + (sizeof(int) * 2) + (kMaxHapticBufferSize * sizeof(byte)); public FourCC typeStatic { get { return Type; } } [FieldOffset(0)] InputDeviceCommand baseCommand; [FieldOffset(InputDeviceCommand.kBaseCommandSize)] int channel; [FieldOffset(InputDeviceCommand.kBaseCommandSize + sizeof(int))] int bufferSize; [FieldOffset(InputDeviceCommand.kBaseCommandSize + (sizeof(int) * 2))] fixed byte buffer[kMaxHapticBufferSize]; public static SendBufferedHapticCommand Create(byte[] rumbleBuffer) { if (rumbleBuffer == null) throw new System.ArgumentNullException(nameof(rumbleBuffer)); int rumbleBufferSize = Mathf.Min(kMaxHapticBufferSize, rumbleBuffer.Length); SendBufferedHapticCommand newCommand = new SendBufferedHapticCommand { baseCommand = new InputDeviceCommand(Type, kSize), bufferSize = rumbleBufferSize }; //TODO TOMB: There must be a more effective, bulk copy operation for fixed buffers than this. //Replace if found. SendBufferedHapticCommand* commandPtr = &newCommand; fixed(byte* src = rumbleBuffer) { for (int cpyIndex = 0; cpyIndex < rumbleBufferSize; cpyIndex++) commandPtr->buffer[cpyIndex] = src[cpyIndex]; } return newCommand; } } }
35.103448
122
0.639489
[ "MIT" ]
ojaypopedev/SwatTime
SwatTime/Library/PackageCache/com.unity.inputsystem@1.0.0-preview/InputSystem/Plugins/XR/Haptics/SendBufferedHapticsCommand.cs
2,036
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using System.Globalization; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace namespace UnitsNet { /// <summary> /// Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units. /// </summary> // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. public sealed partial class Level : IQuantity { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly double _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly LevelUnit? _unit; static Level() { BaseDimensions = BaseDimensions.Dimensionless; Info = new QuantityInfo(QuantityType.Level, Units.Cast<Enum>().ToArray(), BaseUnit, Zero, BaseDimensions); } /// <summary> /// Creates the quantity with a value of 0 in the base unit Decibel. /// </summary> /// <remarks> /// Windows Runtime Component requires a default constructor. /// </remarks> public Level() { _value = 0; _unit = BaseUnit; } /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unit">The unit representation to construct this quantity with.</param> /// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> private Level(double value, LevelUnit unit) { if(unit == LevelUnit.Undefined) throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } #region Static Properties /// <summary> /// Information about the quantity type, such as unit values and names. /// </summary> internal static QuantityInfo Info { get; } /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public static BaseDimensions BaseDimensions { get; } /// <summary> /// The base unit of Level, which is Decibel. All conversions go via this value. /// </summary> public static LevelUnit BaseUnit { get; } = LevelUnit.Decibel; /// <summary> /// Represents the largest possible value of Level /// </summary> public static Level MaxValue { get; } = new Level(double.MaxValue, BaseUnit); /// <summary> /// Represents the smallest possible value of Level /// </summary> public static Level MinValue { get; } = new Level(double.MinValue, BaseUnit); /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public static QuantityType QuantityType { get; } = QuantityType.Level; /// <summary> /// All units of measurement for the Level quantity. /// </summary> public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast<LevelUnit>().Except(new LevelUnit[]{ LevelUnit.Undefined }).ToArray(); /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. /// </summary> public static Level Zero { get; } = new Level(0, BaseUnit); #endregion #region Properties /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => Convert.ToDouble(_value); /// <inheritdoc cref="IQuantity.Unit"/> object IQuantity.Unit => Unit; /// <summary> /// The unit this quantity was constructed with -or- <see cref="BaseUnit" /> if default ctor was used. /// </summary> public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); internal QuantityInfo QuantityInfo => Info; /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public QuantityType Type => Level.QuantityType; /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public BaseDimensions Dimensions => Level.BaseDimensions; #endregion #region Conversion Properties /// <summary> /// Get Level in Decibels. /// </summary> public double Decibels => As(LevelUnit.Decibel); /// <summary> /// Get Level in Nepers. /// </summary> public double Nepers => As(LevelUnit.Neper); #endregion #region Static Methods /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> public static string GetAbbreviation(LevelUnit unit) { return GetAbbreviation(unit, null); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static string GetAbbreviation(LevelUnit unit, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } #endregion #region Static Factory Methods /// <summary> /// Get Level from Decibels. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Level FromDecibels(double decibels) { double value = (double) decibels; return new Level(value, LevelUnit.Decibel); } /// <summary> /// Get Level from Nepers. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Level FromNepers(double nepers) { double value = (double) nepers; return new Level(value, LevelUnit.Neper); } /// <summary> /// Dynamically convert from value and unit enum <see cref="LevelUnit" /> to <see cref="Level" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>Level unit value.</returns> // Fix name conflict with parameter "value" [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] public static Level From(double value, LevelUnit fromUnit) { return new Level((double)value, fromUnit); } #endregion #region Static Parse Methods /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static Level Parse(string str) { return Parse(str, null); } /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static Level Parse(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.Parse<Level, LevelUnit>( str, provider, From); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse([CanBeNull] string str, out Level result) { return TryParse(str, null, out result); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Level result) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.TryParse<Level, LevelUnit>( str, provider, From, out result); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static LevelUnit ParseUnit(string str) { return ParseUnit(str, null); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.Parse<LevelUnit>(str, provider); } public static bool TryParseUnit(string str, out LevelUnit unit) { return TryParseUnit(str, null, out unit); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out LevelUnit unit) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.TryParse<LevelUnit>(str, provider, out unit); } #endregion #region Equality / IComparable public int CompareTo(object obj) { if(obj is null) throw new ArgumentNullException(nameof(obj)); if(!(obj is Level objLevel)) throw new ArgumentException("Expected type Level.", nameof(obj)); return CompareTo(objLevel); } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods internal int CompareTo(Level other) { return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } [Windows.Foundation.Metadata.DefaultOverload] public override bool Equals(object obj) { if(obj is null || !(obj is Level objLevel)) return false; return Equals(objLevel); } public bool Equals(Level other) { return _value.Equals(other.AsBaseNumericType(this.Unit)); } /// <summary> /// <para> /// Compare equality to another Level within the given absolute or relative tolerance. /// </para> /// <para> /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of /// this quantity's value to be considered equal. /// <example> /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Relative); /// </code> /// </example> /// </para> /// <para> /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. /// <example> /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Absolute); /// </code> /// </example> /// </para> /// <para> /// Note that it is advised against specifying zero difference, due to the nature /// of floating point operations and using System.Double internally. /// </para> /// </summary> /// <param name="other">The other quantity to compare to.</param> /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> /// <param name="comparisonType">The comparison type: either relative or absolute.</param> /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> public bool Equals(Level other, double tolerance, ComparisonType comparisonType) { if(tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); double thisValue = (double)this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current Level.</returns> public override int GetHashCode() { return new { QuantityType, Value, Unit }.GetHashCode(); } #endregion #region Conversion Methods double IQuantity.As(object unit) => As((LevelUnit)unit); /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public double As(LevelUnit unit) { if(Unit == unit) return Convert.ToDouble(Value); var converted = AsBaseNumericType(unit); return Convert.ToDouble(converted); } /// <summary> /// Converts this Level to another Level with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A Level with the specified unit.</returns> public Level ToUnit(LevelUnit unit) { var convertedValue = AsBaseNumericType(unit); return new Level(convertedValue, unit); } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private double AsBaseUnit() { switch(Unit) { case LevelUnit.Decibel: return _value; case LevelUnit.Neper: return (1/0.115129254)*_value; default: throw new NotImplementedException($"Can not convert {Unit} to base units."); } } private double AsBaseNumericType(LevelUnit unit) { if(Unit == unit) return _value; var baseUnitValue = AsBaseUnit(); switch(unit) { case LevelUnit.Decibel: return baseUnitValue; case LevelUnit.Neper: return 0.115129254*baseUnitValue; default: throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } } #endregion #region ToString Methods /// <summary> /// Get default string representation of value and unit. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return ToString(null); } /// <summary> /// Get string representation of value and unit. Using two significant digits after radix. /// </summary> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName) { var provider = cultureName; return ToString(provider, 2); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString(string cultureName, int significantDigitsAfterRadix) { var provider = cultureName; var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implicitly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { var provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? GlobalConfiguration.DefaultCulture; var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) { return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; } } }
44.215719
223
0.595817
[ "MIT-feh" ]
Angerxzer/UnitsNet
UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Level.g.cs
26,443
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the workmail-2017-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.WorkMail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkMail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteAccessControlRule operation /// </summary> public class DeleteAccessControlRuleResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteAccessControlRuleResponse response = new DeleteAccessControlRuleResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("OrganizationNotFoundException")) { return OrganizationNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("OrganizationStateException")) { return OrganizationStateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonWorkMailException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteAccessControlRuleResponseUnmarshaller _instance = new DeleteAccessControlRuleResponseUnmarshaller(); internal static DeleteAccessControlRuleResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteAccessControlRuleResponseUnmarshaller Instance { get { return _instance; } } } }
39
192
0.655464
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/WorkMail/Generated/Model/Internal/MarshallTransformations/DeleteAccessControlRuleResponseUnmarshaller.cs
4,017
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ namespace Microsoft.PythonTools.Parsing.Ast { public class BreakStatement : Statement { public BreakStatement() { } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { } walker.PostWalk(this); } } }
35.928571
98
0.563618
[ "Apache-2.0" ]
rsumner33/PTVS
Release/Product/Python/Analysis/Parsing/Ast/BreakStatement.cs
1,006
C#
using Abp.Application.Services; using Abp.Application.Services.Dto; using Abp.Domain.Repositories; using CarPlusGo.CVAS.Accessories.Dto; using System.Linq; using System.Threading.Tasks; using Abp.Extensions; using Abp.Linq.Extensions; namespace CarPlusGo.CVAS.Accessories { public class AccessoriesMainTypeAppService : AsyncCrudAppService<AccessoriesMainType, AccessoriesMainTypeDto, long, PagedAccessoriesMainTypeResultRequestDto, AccessoriesMainTypeDto, AccessoriesMainTypeDto>, IAccessoriesMainTypeAppService { public AccessoriesMainTypeAppService(IRepository<AccessoriesMainType, long> repository) : base(repository) { } protected override IQueryable<AccessoriesMainType> CreateFilteredQuery(PagedAccessoriesMainTypeResultRequestDto input) { return Repository.GetAll() .WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.AccessoriesMainName.Contains(input.Keyword)); } [RemoteService(false)] public override Task Delete(EntityDto<long> input) { return new Task(() => { }); } } }
34.545455
202
0.721053
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
MakingBugs/carplusgo.cvas
src/CarPlusGo.CVAS.Application/Accessories/AccessoriesMainType/AccessoriesMainTypeAppService.cs
1,142
C#
using LuduStack.Domain.Interfaces.Repository; using LuduStack.Domain.Messaging.Queries.Base; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace LuduStack.Domain.Messaging.Queries.UserContent { public class GetUserContentQuery : GetBaseQuery<Models.UserContent> { public GetUserContentQuery() { } public GetUserContentQuery(Expression<Func<Models.UserContent, bool>> where) : base(where) { } } public class GetUserContentQueryHandler : GetBaseQueryHandler<GetUserContentQuery, Models.UserContent, IUserContentRepository> { public GetUserContentQueryHandler(IUserContentRepository repository) : base(repository) { } public new async Task<IEnumerable<Models.UserContent>> Handle(GetUserContentQuery request, CancellationToken cancellationToken) { IEnumerable<Models.UserContent> all = await base.Handle(request, cancellationToken); return all; } } }
31.085714
135
0.719669
[ "MIT" ]
anteatergames/ludustack
LuduStack.Domain.Messaging/Queries/UserContent/GetUserContentQuery.cs
1,090
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using Xunit; namespace System.Diagnostics.TextWriterTraceListenerTests { public class TextWriterTraceListener_WriteTests : IDisposable { private readonly Stream _stream; private readonly string _fileName; private const string TestMessage = "HelloWorld"; public TextWriterTraceListener_WriteTests() { _fileName = string.Format("{0}.xml", GetType().Name); CommonUtilities.DeleteFile(_fileName); _stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write); } [Fact] public void TestWrite() { using (var target = new TextWriterTraceListener(_stream)) { target.Write(TestMessage); } Assert.Contains(TestMessage, File.ReadAllText(_fileName)); } [Fact] public void TestWriteLine() { using (var target = new TextWriterTraceListener(_stream)) { target.WriteLine(TestMessage); } string expected = TestMessage + Environment.NewLine; Assert.Contains(expected, File.ReadAllText(_fileName)); } [Fact] public void TestFlush() { using (var target = new TextWriterTraceListener(_stream)) { target.Write(TestMessage); target.Flush(); } } [Fact] public void TestWriteAfterDisposeShouldNotThrow() { var target = new TextWriterTraceListener(_stream); target.Dispose(); target.WriteLine(TestMessage); target.Write(TestMessage); target.Flush(); } [Fact] public void TestWriterPropery() { var testWriter = new StreamWriter(_stream); using (var target = new TextWriterTraceListener()) { Assert.Null(target.Writer); target.Writer = testWriter; Assert.NotNull(target.Writer); Assert.Same(testWriter, target.Writer); } } public void Dispose() { _stream.Dispose(); CommonUtilities.DeleteFile(_fileName); } } }
28.627907
101
0.564175
[ "MIT" ]
690486439/corefx
src/System.Diagnostics.TextWriterTraceListener/tests/TextWriterTraceListener_WriteTests.cs
2,462
C#
/* * Copyright 2015-2018 Mohawk College of Applied Arts and Technology * * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * User: fyfej * Date: 2017-9-1 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenIZ.Mobile.Core.Services; using System.Net; using OpenIZ.Mobile.Core.Xamarin.Threading; using System.Threading; using System.Net.Sockets; using System.Globalization; using OpenIZ.Mobile.Core.Configuration; using System.IO; using OpenIZ.Mobile.Core.Xamarin.Security; using System.Security; using OpenIZ.Core.Applets.Model; using OpenIZ.Mobile.Core.Diagnostics; using System.Reflection; using OpenIZ.Mobile.Core.Xamarin.Services.Attributes; using OpenIZ.Core.Http; using OpenIZ.Mobile.Core.Xamarin.Resources; using OpenIZ.Core.Applets.ViewModel; using OpenIZ.Core.Model; using OpenIZ.Core.Services; using OpenIZ.Core.Applets.ViewModel.Description; using System.Diagnostics; using OpenIZ.Mobile.Core.Exceptions; using OpenIZ.Core.Applets.ViewModel.Json; using System.IO.Compression; using OpenIZ.Core.Applets.Services; using OpenIZ.Mobile.Core.Security.Audit; using OpenIZ.Core; using OpenIZ.Core.Exceptions; using OpenIZ.Mobile.Core.Xamarin.Services.Model; namespace OpenIZ.Mobile.Core.Xamarin.Services { /// <summary> /// Represents a mini IMS server that the web-view can access /// </summary> public class MiniImsServer : IDaemonService { // Default view model private ViewModelDescription m_defaultViewModel; // Current context [ThreadStatic] public static HttpListenerContext CurrentContext; // Mini-listener private Boolean m_bypassMagic = false; private Boolean m_allowCors = false; private HttpListener m_listener; private Thread m_acceptThread; private Tracer m_tracer = Tracer.GetTracer(typeof(MiniImsServer)); private Dictionary<String, AppletAsset> m_cacheApplets = new Dictionary<string, AppletAsset>(); private object m_lockObject = new object(); private Dictionary<String, InvokationInformation> m_services = new Dictionary<string, InvokationInformation>(); private IContentTypeMapper m_contentTypeHandler = new DefaultContentTypeMapper(); private IThreadPoolService m_threadPool = null; private bool m_startFinished = false; /// <summary> /// Returns true if the service is running /// </summary> public bool IsRunning { get { return this.m_listener?.IsListening == true && this.m_startFinished; } } public event EventHandler Started; public event EventHandler Starting; public event EventHandler Stopped; public event EventHandler Stopping; public bool Start() { try { this.Starting?.Invoke(this, EventArgs.Empty); this.m_tracer.TraceInfo("Starting internal IMS services..."); this.m_threadPool = ApplicationContext.Current.GetService<IThreadPoolService>(); XamarinApplicationContext.Current.SetProgress("IMS Service Bus", 0); this.m_bypassMagic = XamarinApplicationContext.Current.GetType().Name == "MiniApplicationContext"; this.m_tracer.TraceInfo("IMS magic check : {0}", !this.m_bypassMagic); this.m_listener = new HttpListener(); this.m_defaultViewModel = ViewModelDescription.Load(typeof(MiniImsServer).Assembly.GetManifestResourceStream("OpenIZ.Mobile.Core.Xamarin.Resources.ViewModel.xml")); // Scan for services try { foreach (var t in typeof(MiniImsServer).Assembly.DefinedTypes.Where(o => o.GetCustomAttribute<RestServiceAttribute>() != null)) { var serviceAtt = t.GetCustomAttribute<RestServiceAttribute>(); object instance = Activator.CreateInstance(t); foreach (var mi in t.GetRuntimeMethods().Where(o => o.GetCustomAttribute<RestOperationAttribute>() != null)) { var operationAtt = mi.GetCustomAttribute<RestOperationAttribute>(); var faultMethod = operationAtt.FaultProvider != null ? t.GetRuntimeMethod(operationAtt.FaultProvider, new Type[] { typeof(Exception) }) : null; String pathMatch = String.Format("{0}:{1}{2}", operationAtt.Method, serviceAtt.BaseAddress, operationAtt.UriPath); if (!this.m_services.ContainsKey(pathMatch)) lock (this.m_lockObject) this.m_services.Add(pathMatch, new InvokationInformation() { BindObject = instance, Method = mi, FaultProvider = faultMethod, Demand = (mi.GetCustomAttributes<DemandAttribute>().Union(t.GetCustomAttributes<DemandAttribute>())).Select(o => o.PolicyId).ToList(), Anonymous = (mi.GetCustomAttribute<AnonymousAttribute>() ?? t.GetCustomAttribute<AnonymousAttribute>()) != null, Parameters = mi.GetParameters() }); } } } catch (Exception e) { this.m_tracer.TraceWarning("Could scan for handlers : {1}", e); } // Get loopback var loopback = GetLocalIpAddress(); // Core always on 9200 unless overridden var portSetting = ApplicationContext.Current.Configuration.GetAppSetting("http.port"); if (portSetting != null) this.m_listener.Prefixes.Add(String.Format("http://{0}:{1}/", loopback, portSetting)); else this.m_listener.Prefixes.Add(String.Format("http://{0}:9200/", loopback)); this.m_acceptThread = new Thread(() => { // Process the request while (this.m_listener != null) { try { //var iAsyncResult = this.m_listener.BeginGetContext(null, null); //iAsyncResult.AsyncWaitHandle.WaitOne(); var context = this.m_listener.GetContext(); //this.m_listener.EndGetContext(iAsyncResult); this.m_threadPool.QueueUserWorkItem(TimeSpan.MinValue, this.HandleRequest, context); } catch (Exception e) { this.m_tracer.TraceError("Listener Error: {0}", e); } } }); this.m_listener.Start(); this.m_acceptThread.IsBackground = true; this.m_acceptThread.Start(); this.m_acceptThread.Name = "MiniIMS"; this.m_tracer.TraceInfo("Started internal IMS services..."); // We have to wait for the IAppletManager service to come up or else it is pretty useless this.Started?.Invoke(this, EventArgs.Empty); this.m_startFinished = true; return true; } catch (Exception ex) { this.m_tracer.TraceError("Error starting IMS : {0}", ex); ApplicationContext.Current.Alert(Strings.err_moreThanOneApplication); return false; } } /// <summary> /// Create the specified serializer /// </summary> private JsonViewModelSerializer CreateSerializer(ViewModelDescription viewModelDescription) { var retVal = new JsonViewModelSerializer(); retVal.ViewModel = viewModelDescription ?? this.m_defaultViewModel; retVal.LoadSerializerAssembly(typeof(OpenIZ.Core.Model.Json.Formatter.ActExtensionViewModelSerializer).Assembly); return retVal; } /// <summary> /// Don't know why but the device doesn't have a loopback interface by default? /// </summary> /// <returns></returns> private static string GetLocalIpAddress() { var listener = new TcpListener(IPAddress.Loopback, 0); try { listener.Start(); string address = ((IPEndPoint)listener.LocalEndpoint).Address.ToString(); return address; } finally { listener.Stop(); } } /// <summary> /// Handles a request /// </summary> private void HandleRequest(Object state) { try { HttpListenerContext context = state as HttpListenerContext; var request = context.Request; var response = context.Response; var appletManager = ApplicationContext.Current.GetService<IAppletManagerService>(); #if DEBUG Stopwatch perfTimer = new Stopwatch(); perfTimer.Start(); #endif try { if (!request.RemoteEndPoint.Address.Equals(IPAddress.Loopback) && !request.RemoteEndPoint.Address.Equals(IPAddress.IPv6Loopback) && ApplicationContext.Current.Configuration.GetAppSetting("http.externAllowed") != "true") throw new UnauthorizedAccessException("Only local access allowed"); MiniImsServer.CurrentContext = context; // Services require magic #if !DEBUG if (!this.m_bypassMagic && request.Headers["X-OIZMagic"] != ApplicationContext.Current.ExecutionUuid.ToString() && request.UserAgent != $"OpenIZ-DC {ApplicationContext.Current.ExecutionUuid}") { // Something wierd with the appp, show them the nice message if (request.UserAgent.StartsWith("OpenIZ")) { using (var sw = new StreamWriter(response.OutputStream)) sw.WriteLine("Hmm, something went wrong. For security's sake we can't show the information you requested. Perhaps restarting the application will help"); return; } else if (ApplicationContext.Current.Configuration.GetAppSetting("http.bypassMagic") == ApplicationContext.Current.ExecutionUuid.ToString()) { this.m_bypassMagic = true; this.m_tracer.TraceInfo("MINIMS bypass magic unlocked!"); } else // User is using a browser to try and access this? How dare they { response.AddHeader("Content-Encoding", "gzip"); using (var rdr = typeof(MiniImsServer).Assembly.GetManifestResourceStream("OpenIZ.Mobile.Core.Xamarin.Resources.antihaxor")) rdr.CopyTo(response.OutputStream); return; } } #endif if (!String.IsNullOrEmpty(ApplicationContext.Current.Configuration.GetAppSetting("http.cors"))) { response.Headers.Add("Access-Control-Allow-Origin", ApplicationContext.Current.Configuration.GetAppSetting("http.cors")); response.Headers.Add("Access-Control-Allow-Headers", "*"); response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE, PATCH, NULLIFY"); } this.m_tracer.TraceVerbose("Client has the right magic word"); // Session cookie? if (request.Cookies["_s"] != null) { var cookie = request.Cookies["_s"]; if (!cookie.Expired) { var smgr = ApplicationContext.Current.GetService<ISessionManagerService>(); var session = smgr.Get(Guid.Parse(cookie.Value)); if (session != null) { try { AuthenticationContext.Current = AuthenticationContext.CurrentUIContext = new AuthenticationContext(session); this.m_tracer.TraceVerbose("Retrieved session {0} from cookie", session?.Key); } catch (SessionExpiredException) { this.m_tracer.TraceWarning("Session {0} is expired and could not be extended", cookie.Value); response.SetCookie(new Cookie("_s", Guid.Empty.ToString(), "/") { Expired = true, Expires = DateTime.Now.AddSeconds(-20) }); } } else // Something wrong??? Perhaps it is an issue with the thingy? response.SetCookie(new Cookie("_s", Guid.Empty.ToString(), "/") { Expired = true, Expires = DateTime.Now.AddSeconds(-20) }); } } // Authorization header if (request.Headers["Authorization"] != null) { var authHeader = request.Headers["Authorization"].Split(' '); switch (authHeader[0].ToLowerInvariant()) // Type / scheme { case "basic": { var idp = ApplicationContext.Current.GetService<IIdentityProviderService>(); var authString = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader[1])).Split(':'); var principal = idp.Authenticate(authString[0], authString[1]); if (principal == null) throw new UnauthorizedAccessException(); else AuthenticationContext.Current = AuthenticationContext.CurrentUIContext = new AuthenticationContext(principal); this.m_tracer.TraceVerbose("Performed BASIC auth for {0}", AuthenticationContext.Current.Principal.Identity.Name); break; } case "bearer": { var smgr = ApplicationContext.Current.GetService<ISessionManagerService>(); var session = smgr.Get(Guid.Parse(authHeader[1])); if (session != null) { try { AuthenticationContext.Current = AuthenticationContext.CurrentUIContext = new AuthenticationContext(session); this.m_tracer.TraceVerbose("Retrieved session {0} from cookie", session?.Key); } catch (SessionExpiredException) { this.m_tracer.TraceWarning("Session {0} is expired and could not be extended", authHeader[1]); throw new UnauthorizedAccessException("Session is expired"); } } else // Something wrong??? Perhaps it is an issue with the thingy? throw new UnauthorizedAccessException("Session is invalid"); break; } } } // Attempt to find a service which implements the path var rootPath = String.Format("{0}:{1}", request.HttpMethod.ToUpper(), request.Url.AbsolutePath); if (request.Url.AbsolutePath == "/" && ApplicationContext.Current.Configuration.GetAppSetting("http.index") != null) { response.StatusCode = 302; response.RedirectLocation = $"{request.Url.Scheme}://{request.Url.Host}:{request.Url.Port}{ApplicationContext.Current.Configuration.GetAppSetting("http.index")}"; return; } InvokationInformation invoke = null; this.m_tracer.TraceVerbose("Performing service matching on {0}", rootPath); if (this.m_services.TryGetValue(rootPath, out invoke)) { this.m_tracer.TraceVerbose("Matched path {0} to handler {1}.{2}", rootPath, invoke.BindObject.GetType().FullName, invoke.Method.Name); // Get the method information var parmInfo = invoke.Parameters; object result = null; try { // Method demand? foreach (var itm in invoke.Demand) new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, itm).Demand(); // Invoke method if (parmInfo.Length == 0) result = invoke.Method.Invoke(invoke.BindObject, new object[] { }); else { if (parmInfo[0].GetCustomAttribute<RestMessageAttribute>()?.MessageFormat == RestMessageFormat.SimpleJson) { using (StreamReader sr = new StreamReader(request.InputStream)) { var pValue = this.CreateSerializer(null).DeSerialize(sr, parmInfo[0].ParameterType); result = invoke.Method.Invoke(invoke.BindObject, new object[] { pValue }); } } else { var serializer = this.m_contentTypeHandler.GetSerializer(request.ContentType, parmInfo[0].ParameterType); var pValue = serializer.DeSerialize(request.InputStream); result = invoke.Method.Invoke(invoke.BindObject, new object[] { pValue }); } } response.StatusCode = 200; } catch (Exception e) { result = this.HandleServiceException(e, invoke, response); if (result == null) throw; } // Serialize the response if (request.Headers["Accept"] != null && invoke.Method.ReturnParameter.GetCustomAttribute<RestMessageAttribute>()?.MessageFormat != RestMessageFormat.Raw && invoke.Method.ReturnParameter.GetCustomAttribute<RestMessageAttribute>()?.MessageFormat != RestMessageFormat.SimpleJson) { var serializer = this.m_contentTypeHandler.GetSerializer(request.Headers["Accept"].Split(',')[0], result?.GetType() ?? typeof(IdentifiedData)); if (serializer != null) { response.ContentType = request.Headers["Accept"].Split(',')[0]; serializer.Serialize(response.OutputStream, result); } else throw new ArgumentOutOfRangeException(Strings.err_invalid_accept); } else // Use the contract values switch (invoke.Method.ReturnParameter.GetCustomAttribute<RestMessageAttribute>().MessageFormat) { case RestMessageFormat.Raw: response.AddHeader("Content-Security-Policy", "style-src 'unsafe-inline'"); response.AddHeader("Content-Encoding", "deflate"); using (var gzs = new DeflateStream(response.OutputStream, CompressionMode.Compress)) { if (result is Stream) (result as Stream).CopyTo(gzs); else { var br = result as Byte[] ?? Encoding.UTF8.GetBytes(result as String); gzs.Write(br, 0, br.Length); } } break; case RestMessageFormat.SimpleJson: response.ContentType = "application/json"; if (result is IdentifiedData) { response.AddHeader("Content-Encoding", "deflate"); using (var gzs = new DeflateStream(response.OutputStream, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gzs)) { if (request.QueryString["_viewModel"] != null) { var viewModelDescription = appletManager.Applets.GetViewModelDescription(request.QueryString["_viewModel"]); var serializer = this.CreateSerializer(viewModelDescription); serializer.Serialize(sw, (result as IdentifiedData).GetLocked()); } else { this.CreateSerializer(null).Serialize(sw, (result as IdentifiedData).GetLocked()); } } } else if (result != null) this.m_contentTypeHandler.GetSerializer("application/json", result.GetType()).Serialize(response.OutputStream, result); break; case RestMessageFormat.Json: response.ContentType = "application/json"; response.AddHeader("Content-Encoding", "deflate"); using (var gzs = new DeflateStream(response.OutputStream, CompressionMode.Compress)) this.m_contentTypeHandler.GetSerializer("application/json", invoke.Method.ReturnType).Serialize(gzs, result); break; case RestMessageFormat.Xml: response.ContentType = "application/xml"; this.m_contentTypeHandler.GetSerializer("application/xml", invoke.Method.ReturnType).Serialize(response.OutputStream, result); break; } } else if (request.HttpMethod.ToUpper() == "OPTIONS") { response.StatusCode = 200; } else this.HandleAssetRenderRequest(request, response); } catch (UnauthorizedAccessException ex) { this.m_tracer.TraceError("Unauthorized action: {0}", ex.Message); AuditUtil.AuditRestrictedFunction(ex, request.Url); response.StatusCode = 403; var errAsset = appletManager.Applets.ResolveAsset("/org.openiz.core/views/errors/403.html"); var buffer = appletManager.Applets.RenderAssetContent(errAsset, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); response.OutputStream.Write(buffer, 0, buffer.Length); } catch (SecurityException ex) { this.m_tracer.TraceError("General security exception: {0}", ex.Message); if (AuthenticationContext.CurrentUIContext.Principal == AuthenticationContext.AnonymousPrincipal) { // Is there an authentication asset in the configuration var authentication = XamarinApplicationContext.Current.Configuration.GetSection<AppletConfigurationSection>().AuthenticationAsset; if (String.IsNullOrEmpty(authentication)) authentication = appletManager.Applets.AuthenticationAssets.FirstOrDefault(); if (String.IsNullOrEmpty(authentication)) authentication = "/org/openiz/core/views/security/login.html"; string redirectLocation = String.Format("{0}", authentication, request.RawUrl); response.Redirect(redirectLocation); } else { response.StatusCode = 403; var errAsset = appletManager.Applets.ResolveAsset("/org.openiz.core/views/errors/403.html"); var buffer = appletManager.Applets.RenderAssetContent(errAsset, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); response.OutputStream.Write(buffer, 0, buffer.Length); } } catch (FileNotFoundException ex) { this.m_tracer.TraceError(ex.Message); response.StatusCode = 404; var errAsset = appletManager.Applets.ResolveAsset("/org.openiz.core/views/errors/404.html"); var buffer = appletManager.Applets.RenderAssetContent(errAsset, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); response.OutputStream.Write(buffer, 0, buffer.Length); } catch (Exception ex) { this.m_tracer.TraceError("Internal applet error: {0}", ex.ToString()); response.StatusCode = 500; var errAsset = appletManager.Applets.ResolveAsset("/org.openiz.core/views/errors/500.html"); var buffer = appletManager.Applets.RenderAssetContent(errAsset, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); buffer = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(buffer).Replace("{{ exception }}", ex.ToString())); response.OutputStream.Write(buffer, 0, buffer.Length); } finally { try { #if DEBUG perfTimer.Stop(); this.m_tracer.TraceVerbose("PERF : MiniIMS >>>> {0} took {1} ms to service", request.Url, perfTimer.ElapsedMilliseconds); #endif #if DEBUG response.AddHeader("Cache-Control", "no-cache"); #else response.AddHeader("Cache-Control", "no-store"); #endif response.Close(); } catch { } MiniImsServer.CurrentContext = null; } } catch (Exception e) { this.m_tracer.TraceWarning("General exception on listener: {0}", e); } } /// <summary> /// Handles a service exception /// </summary> private object HandleServiceException(Exception e, InvokationInformation invoke, HttpListenerResponse response) { #if DEBUG var ie = e; while (ie != null) { this.m_tracer.TraceError("{0} - ({1}){2} - {3}", e == ie ? "" : "Caused By", invoke.Method.Name, ie.GetType().FullName, ie.Message); ie = ie.InnerException; } #else if (e is TargetInvocationException) this.m_tracer.TraceError("{0} - {1} / {2}", invoke.Method.Name, e.Message, e.InnerException?.Message); else this.m_tracer.TraceError("{0} - {1}", invoke.Method.Name, e.Message); #endif response.StatusCode = 500; if (e is SecurityException) { response.StatusCode = 401; return invoke.FaultProvider?.Invoke(invoke.BindObject, new object[] { e }); } else if (e is FileNotFoundException) { response.StatusCode = 404; return invoke.FaultProvider?.Invoke(invoke.BindObject, new object[] { e }); } else if (e is UnauthorizedAccessException) { response.StatusCode = 403; return invoke.FaultProvider?.Invoke(invoke.BindObject, new object[] { e }); } else if (e is DetectedIssueException) { return new ErrorResult(e); } else if (e is TargetInvocationException) return this.HandleServiceException(e.InnerException, invoke, response); else { return invoke.FaultProvider?.Invoke(invoke.BindObject, new object[] { e }); } } /// <summary> /// Handles the process of rendering an asset. /// </summary> /// <param name="request">The HTTP request.</param> /// <param name="response">The HTTP response.</param> private void HandleAssetRenderRequest(HttpListenerRequest request, HttpListenerResponse response) { // Try to demand policy // Navigate asset AppletAsset navigateAsset = null; var appletManagerService = ApplicationContext.Current.GetService<IAppletManagerService>(); String appletPath = request.Url.AbsolutePath.ToLower(); if (!this.m_cacheApplets.TryGetValue(appletPath, out navigateAsset)) { navigateAsset = appletManagerService.Applets.ResolveAsset(appletPath); if (navigateAsset == null) { throw new FileNotFoundException(request.RawUrl); } lock (m_lockObject) { if (!this.m_cacheApplets.ContainsKey(appletPath)) { this.m_cacheApplets.Add(appletPath, navigateAsset); } } } #if DEBUG response.AddHeader("Cache-Control", "no-cache"); #else if (request.Url.ToString().EndsWith(".js") || request.Url.ToString().EndsWith(".css") || request.Url.ToString().EndsWith(".png") || request.Url.ToString().EndsWith(".woff2")) { response.AddHeader("Cache-Control", "public"); response.AddHeader("Expires", DateTime.UtcNow.AddHours(1).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'")); } else response.AddHeader("Cache-Control", "no-cache"); #endif // Navigate policy? if (navigateAsset.Policies != null) { foreach (var policy in navigateAsset.Policies) { new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, policy).Demand(); } } response.ContentType = navigateAsset.MimeType; // Write asset var content = appletManagerService.Applets.RenderAssetContent(navigateAsset, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); response.AddHeader("Content-Encoding", "deflate"); using (var gzs = new DeflateStream(response.OutputStream, CompressionMode.Compress)) gzs.Write(content, 0, content.Length); } /// <summary> /// Stop the listener /// </summary> public bool Stop() { this.Stopping?.Invoke(this, EventArgs.Empty); this.m_tracer?.TraceInfo("Stopping IMS services..."); this.m_listener?.Stop(); this.m_listener = null; this.Stopped?.Invoke(this, EventArgs.Empty); return true; } /// <summary> /// Represents service invokation information /// </summary> private class InvokationInformation { /// <summary> /// Allow anonymous access /// </summary> public bool Anonymous { get; internal set; } /// <summary> /// Bind object /// </summary> public Object BindObject { get; set; } /// <summary> /// Gets the demand for the overall object /// </summary> public List<String> Demand { get; internal set; } /// <summary> /// Fault provider /// </summary> public MethodInfo FaultProvider { get; set; } /// <summary> /// The method for the specified URL template /// </summary> public MethodInfo Method { get; set; } /// <summary> /// The list of parameters /// </summary> public ParameterInfo[] Parameters { get; set; } } } }
48.867847
186
0.505172
[ "Apache-2.0" ]
MohawkMEDIC/openizdc
OpenIZ.Mobile.Core.Xamarin/Services/MiniImsServer.cs
35,869
C#
namespace DotNetCSS.Tests { using DotNetCSS; using System; using Xunit; //[TestFixture] public class MediaListTests : CssConstructionFunctions { [Fact] public void SimpleScreenMediaList() { var source = @"@media screen { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("screen", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void MediaListAtIllegal() { var source = @"@media @screen { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void MediaListInterrupted() { var source = @"@media screen; h1 { color: green }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<StyleRule>(sheet.Rules[0]); var h1 = (StyleRule)sheet.Rules[0]; Assert.Equal("h1", h1.SelectorText); var style = h1.Style; Assert.Equal("rgb(0, 128, 0)", style.Color); } [Fact] public void SimpleScreenTvMediaList() { var source = @"@media screen,tv { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("screen, tv", media.Media.MediaText); var list = media.Media; Assert.Equal(2, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void SimpleScreenTvSpacesMediaList() { var source = @"@media screen , tv { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("screen, tv", media.Media.MediaText); var list = media.Media; Assert.Equal(2, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void OnlyScreenTvMediaList() { var source = @"@media only screen,tv { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("only screen, tv", media.Media.MediaText); var list = media.Media; Assert.Equal(2, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void NotScreenTvMediaList() { var source = @"@media not screen,tv { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("not screen, tv", media.Media.MediaText); var list = media.Media; Assert.Equal(2, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void FeatureMinWidthMediaList() { var source = @"@media (min-width:30px) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("(min-width: 30px)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void OnlyFeatureWidthMediaList() { var source = @"@media only (width: 640px) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("only (width: 640px)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void NotFeatureDeviceWidthMediaList() { var source = @"@media not (device-width: 640px) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("not (device-width: 640px)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void AllFeatureMaxWidthMediaListMissingAnd() { var source = @"@media all (max-width:30px) { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void NoMediaQueryGivenSkip() { var source = @"@media { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void NotNoMediaTypeOrExpressionSkip() { var source = @"@media not { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void OnlyNoMediaTypeOrExpressionSkip() { var source = @"@media only { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void MediaFeatureMissingSkip() { var source = @"@media () { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void MediaFeatureMissingSkipReadNext() { var source = @"@media () { h1 { color: red } } h1 { color: green }"; var sheet = ParseStyleSheet(source); Assert.Equal(2, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); Assert.IsType<StyleRule>(sheet.Rules[1]); var style = (StyleRule)sheet.Rules[1]; Assert.Equal("rgb(0, 128, 0)", style.Style.Color); Assert.Equal("h1", style.SelectorText); } [Fact] public void FeatureMaxWidthMediaListMissingConnectedAnd() { var source = @"@media (max-width:30px) (min-width:10px) { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void TvScreenMediaListMissingComma() { var source = @"@media tv screen { h1 { color: red } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.Equal(RuleType.Media, sheet.Rules[0].Type); var media = sheet.Rules[0] as MediaRule; Assert.Equal("not all", media.ConditionText); Assert.Equal(1, media.Rules.Length); } [Fact] public void AllFeatureMaxWidthMediaListWithAndKeyword() { var source = @"@media all and (max-width:30px) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("all and (max-width: 30px)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void FeatureAspectRatioMediaList() { var source = @"@media (aspect-ratio: 16/9) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("(aspect-ratio: 16/9)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void PrintFeatureMaxWidthAndMinDeviceWidthMediaList() { var source = @"@media print and (max-width:30px) and (min-device-width:100px) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("print and (max-width: 30px) and (min-device-width: 100px)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void AllFeatureMinWidthAndMinDeviceWidthScreenMediaList() { var source = @"@media all and (min-width:0) and (min-device-width:100px), screen { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("all and (min-width: 0) and (min-device-width: 100px), screen", media.Media.MediaText); var list = media.Media; Assert.Equal(2, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void ImplicitAllFeatureResolutionMediaList() { var source = @"@media (resolution:72dpi) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("(resolution: 72dpi)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void ImplicitAllFeatureMinResolutionAndMaxResolutionMediaList() { var source = @"@media (min-resolution:72dpi) and (max-resolution:140dpi) { h1 { color: green } }"; var sheet = ParseStyleSheet(source); Assert.Equal(1, sheet.Rules.Length); Assert.IsType<MediaRule>(sheet.Rules[0]); var media = (MediaRule)sheet.Rules[0]; Assert.Equal("(min-resolution: 72dpi) and (max-resolution: 140dpi)", media.Media.MediaText); var list = media.Media; Assert.Equal(1, list.Length); Assert.Equal(1, media.Rules.Length); } [Fact] public void CssMediaListApiWithAppendDeleteAndTextShouldWork() { var media = new [] { "handheld", "screen", "only screen and (max-device-width: 480px)" }; var p = new StylesheetParser(); var m = new MediaList(p); Assert.Equal(0, m.Length); m.Add(media[0]); m.Add(media[1]); m.Add(media[2]); m.Remove(media[1]); Assert.Equal(2, m.Length); Assert.Equal(media[0], m[0]); Assert.Equal(media[2], m[1]); Assert.Equal(String.Concat(media[0], ", ", media[2]), m.MediaText); } } }
35.133501
112
0.546817
[ "MIT" ]
grapoza/DotNetCSS
src/DotNetCSS.Tests/MediaListTests.cs
13,950
C#
// context.cs // // Copyright 2010 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.ComponentModel; namespace Microsoft.Ajax.Utilities { public class Context { public DocumentContext Document { get; private set; } public int StartLineNumber { get; internal set; } public int StartLinePosition { get; internal set; } public int StartPosition { get; internal set; } public int EndLineNumber { get; internal set; } public int EndLinePosition { get; internal set; } public int EndPosition { get; internal set; } public int SourceOffsetStart { get; internal set; } public int SourceOffsetEnd { get; internal set; } /// <summary> /// Gets and sets the output start line after running an AST through an output visitor /// </summary> public int OutputLine { get; set; } /// <summary> /// Gets and sets the output start column after running an AST through an output visitor /// </summary> public int OutputColumn { get; set; } public JSToken Token { get; internal set; } public int StartColumn { get { return StartPosition - StartLinePosition; } } public int EndColumn { get { return EndPosition - EndLinePosition; } } public bool HasCode { get { return !Document.IsGenerated && EndPosition > StartPosition && EndPosition <= Document.Source.Length && EndPosition != StartPosition; } } public String Code { get { return (!Document.IsGenerated && EndPosition > StartPosition && EndPosition <= Document.Source.Length) ? Document.Source.Substring(StartPosition, EndPosition - StartPosition) : null; } } private string ErrorSegment { get { string source = this.Document.Source; // just pull out the string that's between start position and end position if (this.StartPosition >= source.Length) { return string.Empty; } else { int length = this.EndPosition - this.StartPosition; if (this.StartPosition + length <= source.Length) { return source.Substring(this.StartPosition, length).Trim(); } else { return source.Substring(this.StartPosition).Trim(); } } } } public Context(DocumentContext document) { if (document == null) { throw new ArgumentNullException("document"); } Document = document; StartLineNumber = 1; EndLineNumber = 1; EndPosition = Document.Source.IfNotNull(s => s.Length); Token = JSToken.None; } public Context(DocumentContext document, int startLineNumber, int startLinePosition, int startPosition, int endLineNumber, int endLinePosition, int endPosition, JSToken token) : this(document) { StartLineNumber = startLineNumber; StartLinePosition = startLinePosition; StartPosition = startPosition; EndLineNumber = endLineNumber; EndLinePosition = endLinePosition; EndPosition = endPosition; Token = token; } public Context Clone() { return new Context(this.Document) { StartLineNumber = this.StartLineNumber, StartLinePosition = this.StartLinePosition, StartPosition = this.StartPosition, EndLineNumber = this.EndLineNumber, EndLinePosition = this.EndLinePosition, EndPosition = this.EndPosition, SourceOffsetStart = this.SourceOffsetStart, SourceOffsetEnd = this.SourceOffsetEnd, Token = this.Token, }; } public Context FlattenToStart() { // clone the context and flatten the end to be the start position var clone = Clone(); clone.EndLineNumber = clone.StartLineNumber; clone.EndLinePosition = clone.StartLinePosition; clone.EndPosition = clone.StartPosition; clone.Token = JSToken.None; return clone; } public Context FlattenToEnd() { // clone the context and flatten the start to the end position var clone = Clone(); clone.StartLineNumber = clone.EndLineNumber; clone.StartLinePosition = clone.EndLinePosition; clone.StartPosition = clone.EndPosition; clone.Token = JSToken.None; return clone; } /// <summary> /// Create a new context by combining the current and other contexts /// </summary> /// <param name="other">other context</param> /// <returns>new context instance</returns> public Context CombineWith(Context other) { return this.Clone().UpdateWith(other); } /// <summary> /// Trim off the first few characters of the context and return those characters /// as a new context. Doesn't work if the length crosses a line boundary! /// </summary> /// <param name="length">number of characters to trim off the front of this token</param> /// <returns>context for the trimmed-off portion</returns> public Context SplitStart(int length) { // create the new context for the trimmed-off part // while adjusting this context to start after the trimmed-off part var clone = this.Clone(); clone.EndPosition = this.StartPosition += length; clone.EndLineNumber = clone.StartLineNumber; clone.EndLinePosition = clone.StartLinePosition; return clone; } /// <summary> /// updates the current context with the other context /// </summary> /// <param name="other">other context</param> /// <returns>current context for chaining purposes</returns> public Context UpdateWith(Context other) { if (other != null) { if (other.StartPosition < this.StartPosition) { this.StartPosition = other.StartPosition; this.StartLineNumber = other.StartLineNumber; this.StartLinePosition = other.StartLinePosition; this.SourceOffsetStart = other.SourceOffsetStart; } if (other.EndPosition > this.EndPosition) { this.EndPosition = other.EndPosition; this.EndLineNumber = other.EndLineNumber; this.EndLinePosition = other.EndLinePosition; this.SourceOffsetEnd = other.SourceOffsetEnd; } if (this.Token != other.Token) { this.Token = JSToken.None; } } return this; } public bool Is(JSToken token) { return Token == token; } public bool IsOne(params JSToken[] tokens) { // if any one of the tokens match what we have, we're good if (tokens != null) { var target = this.Token; for (var ndx = tokens.Length - 1; ndx >= 0; --ndx) { if (tokens[ndx] == target) { return true; } } } // otherwise we're not return false; } public bool IsNot(JSToken token) { return Token != token; } public bool IsNotAny(params JSToken[] tokens) { // if any of the tokens match, return false; otherwise we're good. if (tokens != null) { var target = this.Token; for (var ndx = tokens.Length - 1; ndx >= 0; --ndx) { if (tokens[ndx] == target) { return false; } } } return true; } [Localizable(false)] public bool Is(string text) { // the lengths needs to be the same before we'll even TRY looking at the document source. // then verify the values of the indexes into the source, // THEN try doing the text comparison return text != null && EndPosition - StartPosition == text.Length && EndPosition <= Document.Source.Length && StartPosition >= 0 && StartPosition <= EndPosition && string.CompareOrdinal(Document.Source, StartPosition, text, 0, text.Length) == 0; } internal void ReportUndefined(Lookup lookup) { var reference = new UndefinedReference(lookup, this); Document.ReportUndefined(reference); } internal void ChangeFileContext(string fileContext) { // if the file context is the same, then there's nothing to change if (string.Compare(Document.FileContext, fileContext, StringComparison.OrdinalIgnoreCase) != 0) { // different source. Need to create a clone of the current document context but // with the new file context so we don't change the file context for all existing // context objects with the same document. Document = Document.Clone(); Document.FileContext = fileContext; } } public static string GetErrorString(JSError errorCode) { return JScript.ResourceManager.GetString(errorCode.ToString(), JScript.Culture); } internal void HandleError(JSError errorId, bool forceToError = false) { if ((errorId != JSError.UndeclaredVariable && errorId != JSError.UndeclaredFunction) || !Document.HasAlreadySeenErrorFor(Code)) { var severity = GetSeverity(errorId); var errorMessage = GetErrorString(errorId); var context = this.ErrorSegment; if (!context.IsNullOrWhiteSpace()) { errorMessage += CommonStrings.ContextSeparator + context; } var error = new ContextError() { IsError = forceToError || severity < 2, File = Document.FileContext, Severity = severity, Subcategory = ContextError.GetSubcategory(severity), ErrorNumber = (int)errorId, ErrorCode = "JS{0}".FormatInvariant((int)errorId), StartLine = this.StartLineNumber, StartColumn = this.StartColumn + 1, EndLine = this.EndLineNumber, EndColumn = this.EndColumn + 1, Message = errorMessage, }; Document.HandleError(error); } } public bool IsBefore(Context other) { // this context is BEFORE the other context if it starts on an earlier line, // OR if it starts on the same line but at an earlier column // (or if the other context is null) return other == null || StartLineNumber < other.StartLineNumber || (StartLineNumber == other.StartLineNumber && StartColumn < other.StartColumn); } public override string ToString() { return Code; } #region private static methods /// <summary> /// Return the default severity for a given JSError value /// guide: 0 == there will be a run-time error if this code executes /// 1 == the programmer probably did not intend to do this /// 2 == this can lead to cross-browser or future problems. /// 3 == this can lead to performance problems /// 4 == this is just not right /// </summary> /// <param name="errorCode">error code</param> /// <returns>severity</returns> private static int GetSeverity(JSError errorCode) { switch (errorCode) { case JSError.AmbiguousCatchVar: case JSError.AmbiguousNamedFunctionExpression: case JSError.ExportNotAtModuleLevel: case JSError.NumericOverflow: case JSError.StrictComparisonIsAlwaysTrueOrFalse: return 1; case JSError.ArrayLiteralTrailingComma: case JSError.DuplicateCatch: case JSError.DuplicateConstantDeclaration: case JSError.DuplicateLexicalDeclaration: case JSError.HighSurrogate: case JSError.KeywordUsedAsIdentifier: case JSError.LowSurrogate: case JSError.MisplacedFunctionDeclaration: case JSError.ObjectLiteralKeyword: return 2; case JSError.ArgumentNotReferenced: case JSError.DuplicateName: case JSError.FunctionNotReferenced: case JSError.UndeclaredFunction: case JSError.UndeclaredVariable: case JSError.VariableDefinedNotReferenced: return 3; case JSError.FunctionNameMustBeIdentifier: case JSError.ObjectConstructorTakesNoArguments: case JSError.OctalLiteralsDeprecated: case JSError.NewLineNotAllowed: case JSError.NoModuleExport: case JSError.NumericMaximum: case JSError.NumericMinimum: case JSError.SemicolonInsertion: case JSError.StatementBlockExpected: case JSError.SuspectAssignment: case JSError.SuspectEquality: case JSError.SuspectSemicolon: case JSError.UnusedLabel: case JSError.WithNotRecommended: return 4; default: // all others return 0; } } #endregion } }
36.304147
183
0.53459
[ "MIT" ]
TrevorDArcyEvans/EllieWare
Code/WebGrease/Ajax/JavaScript/context.cs
15,756
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; namespace Demo { public enum Verbosity { Quiet, Minimal, Normal, Detailed, Diagnostic } public sealed class VerbosityConverter : TypeConverter { private readonly Dictionary<string, Verbosity> _lookup; public VerbosityConverter() { _lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase) { { "q", Verbosity.Quiet }, { "quiet", Verbosity.Quiet }, { "m", Verbosity.Minimal }, { "minimal", Verbosity.Minimal }, { "n", Verbosity.Normal }, { "normal", Verbosity.Normal }, { "d", Verbosity.Detailed }, { "detailed", Verbosity.Detailed }, { "diag", Verbosity.Diagnostic }, { "diagnostic", Verbosity.Diagnostic } }; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string stringValue) { var result = _lookup.TryGetValue(stringValue, out var verbosity); if (!result) { const string format = "The value '{0}' is not a valid verbosity."; var message = string.Format(CultureInfo.InvariantCulture, format, value); throw new InvalidOperationException(message); } return verbosity; } throw new NotSupportedException("Can't convert value to verbosity."); } } }
31.8
109
0.538022
[ "MIT" ]
0xced/spectre.console
examples/Cli/Demo/Verbosity.cs
1,749
C#
namespace TheCsprojLibrary.ItemTypes { public class _IISApplicationPoolDisplayProxy { public _IISApplicationPoolDisplayProxy(_IISApplicationPool original) { DestinationIISApplicationPool = original.DestinationIISApplicationPool; UnevaluatedInclude = original.UnevaluatedInclude; } public string DestinationIISApplicationPool { get; set; } public string UnevaluatedInclude { get; set; } } }
22.833333
83
0.607664
[ "BSD-2-Clause" ]
Code-Sharp/TheCsprojLibrary
src/TheCsprojLibrary/ItemTypes/_IISApplicationPoolDisplayProxy.cs
548
C#