The call is ambiguous between the following methods: Identical.NameSpace.InitializeComponent() and Identical.NameSpace.InitializeComponent()
Asked Answered
V

13

14

Ok, I suspect this might be a Visual Studio thing, but there must be some reason for this. I created from the list of default items a ListBox (Right Click on project, or folder in project -> Add -> New Item -> Xaml ListBox). Immediately I get a red squiggly line with the error:

"Error 2 The call is ambiguous between the following methods or properties: 'Identical.NameSpace.ListBox1.InitializeComponent()' and 'Identical.NameSpace.ListBox1.InitializeComponent()' C:\Documents and Settings\ouflak\My Documents\Visual Studio 2010\Projects\Identical\NameSpace\ListBox1.xaml.cs 27"

All of the code in question is auto-generated and the reason for the error is because of a conflict between two auto-generated files: ListBox1.g.cs and ListBox1.designer.cs where public void InitializeComponent() is declared in both. Naturally the code cannot compile under this circumstance. It is simple enough to just delete the ListBox1.designer.cs and move on I suppose. But my question: Why is this code auto-generated with this error? I would expect anything auto-generated to be able to build and compile without having to touch the project or any code. For just about every other toobox item that you can add, this is the case. So why generate this code with the built-in error? Are we supposed to find some way to make this work? Is this code merely a suggestion and it is up to the IDE user/developer to hammer out the details?

Here is the generated code: ListBox1.xaml:

< ?xml version="1.0" encoding="utf-8" ? > 
< ListBox
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:xc="http://ns.neurospeech.com/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    x:Class="Identical.NameSpace.ListBox1"
    >
    <sys:String>Item 1</sys:String>
    <sys:String>Item 2</sys:String>
    <sys:String>Item 3</sys:String>
< /ListBox>

ListBox1.g.cs:

namespace Identical.Namespace
{
    /// <summary>
    /// ListBox1
    /// </summary>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    public partial class ListBox1 : System.Windows.Controls.ListBox, System.Windows.Markup.IComponentConnector {

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
            return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/MyProject;component/namespace/listbox1.xaml", System.UriKind.Relative);

            #line 1 "..\..\..\namespace\ListBox1.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target)     {
        this._contentLoaded = true;
        }
    }
}

ListBox1.designer.cs:

namespace Identical.NameSpace
{
    using System;

    public partial class ListBox1 : System.Windows.Controls.ListBox
    {
        private void InitializeComponent()
        {
            // Pre Statements...
            string string1 = "Item 1";
            string string2 = "Item 2";
            string string3 = "Item 3";
            // Statements...
            this.BeginInit();
            this.Items.Add(string1);
            this.Items.Add(string2);
            this.Items.Add(string3);
            this.EndInit();
            // Post Statements...
        }
    }
}

and lastly the ListBox1.xaml.cs (only modified to prevent XML documentation and Stylecop warnings):

namespace Identical.NameSpace
{
    /// <summary>
    /// ListBox1 class
    /// </summary>
    public partial class ListBox1 : ListBox
    {
        /// <summary>
        /// Initializes a new instance of the ListBox1 class
        /// </summary>
        public ListBox1()
        {
            this.InitializeComponent();
        }
    }
}

That's it. This is the code entirely in its virgin auto-generated state with the exception of the comments I put into the xaml.cs file.

I've searched this site and the internet a bit, but no one seems to have explained this behavior. I will probably just delete the designer.cs code and move on. But if anybody knows why this is here in the first place, or if it is indeed a bug in Visual Studio 2010 professional, I'd really like to know.

Vigorous answered 6/12, 2013 at 9:41 Comment(12)
Is this all in a single project? (i.e. is it possible that the other identical namespace is coming from a referenced assembly)?Teocalli
Why do you have removed all namespaces in your code samples?Linea
No problem, I'll add them...Vigorous
The namespaces were auto-generated when the ListBox was added. Again, this is Visual Studio's doing, not mine.Vigorous
See if this helps: unknown error upon rebuilding WPF project. See if you have accidently included the .designer.cs file as part of your project.Rosario
Thanks for the link publicgk, but I haven't touched the project. I simply added the item and that was it.Vigorous
Ok, I've bolded the actual question part of my question. As I state in the question, it is obvious that the multiple definition in the two auto-generated files is the reason for the error. It is relatively trivial to fix this. The question: Why would Visual Studio generate the faulty code in the first place?Vigorous
This doesn't look like the standard IDE. Add->New Item->Xaml ListBox Where is that?Donnadonnamarie
I don't have "Xaml ListBox" either, and I also don't see it in the "Online Templates".Wop
Curious: If you right-click ListBox1.xaml in the solution explorer and click "Run Custom Tool" is the error still there? It seems that's supposed to regen the .g.cs file at least. https://mcmap.net/q/827354/-auto-generated-view-g-cs-page-keeps-including-old-using-statements Either way, I know the question still remains as to why it's generated like this in the first place.Wop
Have heard nothing back from Microsoft regarding this.Vigorous
Just an update: Tested this just now in Visual Studio 2022 and now there's no error anymore. I guess Microsoft finally got some summer intern to take a look at this.Vigorous
V
13

It appears that you have declared the InitializeComponent method in two places in your class, probably one in each partial class. Try searching in all files for InitializeComponent in Visual Studio and I'm guessing that the results will list two places where it is declared. Delete one and the error will disappear.


UPDATE >>>

I'm not sure what kind of answer you're expecting here... clearly, if you didn't add one of those InitializeComponent method definitions, then visual Studio has a bug. I very much doubt that there can be any kind of logical reason for this except that it's a bug.

UPDATE 2 >>>

I had a look on the Microsoft Connect website for any existing reported bugs like this but couldn't find any... I've left the link here if you do want to report it to them.

Villada answered 6/12, 2013 at 9:55 Comment(6)
i haven't declared this code. Ofcourse that's true about the multiple definitions. But again, Visual Studio declared this. Not I! This is auto-generated code. The question is: Why would Visual Studio generate faulty code?Vigorous
RE: UPDATE: Yeah, and I'm perfectly willing to accept this and report it to Microsoft and everything (I've reported other bugs to them in the past). But it's hard to imagine that nobody has tried to add one of these default items from the options and dug into the why of the faulty generation, and/or already reported it to Microsoft. I'd think I would have found that somewhere on the internet. I'll look into the bug reporting mechanism for Visual Studio. It's a macro recording thing they've got setup that you have to install.Vigorous
Have heard nothing back from Microsoft. I kind of get the feeling that they consider this a Visual Studio 2010 thing, and are quite willing to just ignore it, now that two subsequent versions have come out.Vigorous
Anyway +1 for trying to help out. Looks like my company will be upgrading Visual Studio soon out of necessity. I'll see if a similar bug exists there.Vigorous
It's also a Visual Studio 2017 thing.Viator
Anybody tested if this is still happening on 2019?Vigorous
G
14

I had this issue when copying my XAML between controls. I just had to change my x:Class="mynamespace" where mynamespace is the proper namespace for your project. Recompiled and all went back to normal.

Granophyre answered 23/9, 2014 at 17:33 Comment(2)
Interesting. Maybe this will help someone. +1Vigorous
Another one that's caught me in the past is when you've done a cut-n-paste from class A's XAML to class B's XAML and forgot to change the x:Class for B. The compile error can be reported for class A, which is confusing because there's nothing wrong with either the XAML or code-behind for A and no indication that the problem actually lies with another class.Sipple
V
13

It appears that you have declared the InitializeComponent method in two places in your class, probably one in each partial class. Try searching in all files for InitializeComponent in Visual Studio and I'm guessing that the results will list two places where it is declared. Delete one and the error will disappear.


UPDATE >>>

I'm not sure what kind of answer you're expecting here... clearly, if you didn't add one of those InitializeComponent method definitions, then visual Studio has a bug. I very much doubt that there can be any kind of logical reason for this except that it's a bug.

UPDATE 2 >>>

I had a look on the Microsoft Connect website for any existing reported bugs like this but couldn't find any... I've left the link here if you do want to report it to them.

Villada answered 6/12, 2013 at 9:55 Comment(6)
i haven't declared this code. Ofcourse that's true about the multiple definitions. But again, Visual Studio declared this. Not I! This is auto-generated code. The question is: Why would Visual Studio generate faulty code?Vigorous
RE: UPDATE: Yeah, and I'm perfectly willing to accept this and report it to Microsoft and everything (I've reported other bugs to them in the past). But it's hard to imagine that nobody has tried to add one of these default items from the options and dug into the why of the faulty generation, and/or already reported it to Microsoft. I'd think I would have found that somewhere on the internet. I'll look into the bug reporting mechanism for Visual Studio. It's a macro recording thing they've got setup that you have to install.Vigorous
Have heard nothing back from Microsoft. I kind of get the feeling that they consider this a Visual Studio 2010 thing, and are quite willing to just ignore it, now that two subsequent versions have come out.Vigorous
Anyway +1 for trying to help out. Looks like my company will be upgrading Visual Studio soon out of necessity. I'll see if a similar bug exists there.Vigorous
It's also a Visual Studio 2017 thing.Viator
Anybody tested if this is still happening on 2019?Vigorous
P
4

My problem was the project that was giving me the ambiguous call had a reference to its own dll. This was causing the method to be referenced from the dll as well as in the actual project. Once i removed the dll from the references the ambiguous call error went away.

Pavior answered 27/7, 2016 at 14:39 Comment(0)
T
3

Can happen if you are not alert and careful about how you use Resharper.

This happened to me when a I allowed Resharper to auto-import references while I was coding.

So having mistyped initially, then edited the code I was working on, I did not check what it had imported. After running into the same issue, I realised that there was a self-reference in the same library. So there were double implementations of the method in question.

Tadio answered 6/10, 2016 at 13:59 Comment(3)
Had this issue today unfortunately working on a miserable project that uses a Table Adapter XSD file which got totally trashed by ReSharper and probably half the references in the projectMesomorphic
Similar issue, Resharper added a reference to another project, from which I was already using a linked file, hence a double reference. Found it out by looking at git difference in .csproj file.Third
I also had to clear the Resharper cache afterwards to get the errors to go away (ReSharper > Options... > Clear Cache)Third
R
1

Both classes are partial, meaning they share each others non private fields & methods.

Your ListBox1 does have two InitializeComponent (shared) methods. Changing the namespace of either ListBox1 will resolve this error.

Rimini answered 6/12, 2013 at 9:55 Comment(4)
Certainly. But why would Visual Studio auto-generate faulty code in the first place? That is the question.Vigorous
I could understand Visual Studio doing this, if you named two of your listboxes ListBox1Rimini
Again, I have not named or renamed anything. This is all Visual Studio code. This is the only item in the entire solution with this name. And even if there was another listbox in my solution, it would be in a different namespace because this was the only element in that namespace.Vigorous
+1 for trying to help. I suppose this is just a case of the testers of Visual Studio not going through and stumbling across this issue.Vigorous
L
1

I think InitializeComponent() is declared in two different locations in the same class.

Try to find both class definitions using CTR+F and then resolve solve the ambiguity.

Lacerate answered 6/12, 2013 at 9:59 Comment(4)
I think the problem here is that my question is not clear. I will bold the relevant part. Hold on....Vigorous
+1 for the CTRL+F suggestion. I hadn't ever come across that particular feature shortcut.Vigorous
@Vigorous it's one of the most standard options in even the simplest of editing programs, even notepad has it. Some years ago a guy was horrified that his bus driver didn't know about it and publicised it more but still some people have managed not to find it.Madancy
also this only works when it's in the same file. But there could be two files i.e. different names, but with the same class, a partial class. e.g. the main file and the designer oneMadancy
I
1

I ran into this issue, with a user control and an associated style. I think I had tried to move some logic into the style class but it didn't work, so I undid it, but apparently something got left behind.

It was also complaining about the _contentLoaded variable, so I tried deleting the one that was there, and the error went away, and was not replaced with another error. I then hit F12 to go to _contentLoaded's definition and found that it was in the *.g file for the style class. Though the file was named after the style, the class inside was named after the user control.

I deleted the bin and obj folders to resolve it.

Innkeeper answered 16/5, 2016 at 12:17 Comment(0)
M
1

I managed to resolve this by looking inside the .csproj file with a text editor and looking for the name of the Table Adapter XSD file. I found two references to it one with a different alias name hence why I was getting this error message.

Mesomorphic answered 1/11, 2016 at 18:45 Comment(1)
Just to add to my own answer it was due to ReSharper Ultimate (latest trial) that I installed on Visual Studio 2015 CEMesomorphic
M
1

I have just had and resolved this exact thing..

It happened at some point during or after I duplicated a form, in a WinForms program, then renamed it to blah_Copy.

The main cs file and the designer cs file, are both partial classes. So if a method is defined in both and it has the same name and parameters (or same name and same no paramters) , / same signature then it will clash.

In my case they both, both Initialize() { .. } definitions, had identical bodies so I easily just removed one.

Also let's say the method is Initialize() (it was in my case). If you go to call itself, then hit F12 it will go to one of((or perhaps even at least one), of the definitions.

Madancy answered 3/4, 2017 at 22:55 Comment(0)
K
1

I fixed this issue by cleaning up the bin and obj folders. You can try to remove these two folders and then rebuild the solution.

Kristankriste answered 14/8, 2019 at 8:45 Comment(0)
H
1

I had the same problem after changing a bunch of files at once, here's how I fixed it:

  • Find the solution in Solution Explorer (View -> Solution Explorer)
  • Right-click on the solution and click "Clean Solution"

.. and that's it! Visual Studio can be weird sometimes..

Henshaw answered 29/5, 2020 at 13:5 Comment(0)
A
0

After copy and paste, as well as renaming the new class in code, also open the designer and change the name in the first line of the XAML. Build the project. Fixed!

Among answered 26/9, 2020 at 17:2 Comment(1)
Thanks, but 'fixing' this error is not the problem. That's trivial. The problem is that this is showing up by simply relying on the default options and the resulting auto-generated code. No other control is displaying this issue, nor should any really. What version of Visual Studio are you using?Vigorous
I
0

In my case it helped closing Visual Studio, then delete the (possibly hidden) folders .vs and (because I have CodeRush) .cr. Then restart VS and open the project.

Inflationism answered 16/11, 2023 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.